Home > Web Front-end > Vue.js > body text

How to bind data in setup in vue

下次还敢
Release: 2024-05-07 11:45:25
Original
669 people have browsed it

There are three ways to bind Setup data in Vue: 1. refs: use the ref attribute to bind element references to setup variables; 2. v-model: two-way binding of input element values ​​and setup variables; 3. Custom attribute: Create an attribute and bind it to the setup variable. Use this.attributeName to access the value.

How to bind data in setup in vue

Bind Setup data in Vue

In Vue, use setup() Functions define logic and component state. In order to bind this data to the component template, you can use the following methods:

1. refs

  • Use the ref attribute to the element or component reference bound to a variable in the setup.
  • To access bound elements or components, use this.$refs.<ref-name>.

Example:

<code class="vue"><template>
  <input ref="myInput" />
</template>

<script>
import { ref } from 'vue';

export default {
  setup() {
    const inputRef = ref(null);
    return { inputRef };
  },
  mounted() {
    console.log(this.$refs.myInput.value);
  }
};
</script></code>
Copy after login

2. v-model

  • Usev- The model directive binds input element values ​​to variables in the setup.
  • v-model Will bind input values ​​and data variables two-way.

Example:

<code class="vue"><template>
  <input v-model="inputText" />
</template>

<script>
import { ref } from 'vue';

export default {
  setup() {
    const inputText = ref('');
    return { inputText };
  }
};
</script></code>
Copy after login

3. Custom attributes

  • Create custom attributes and It is bound to a variable in setup.
  • To access the bound value, use this.attributeName.

Example:

<code class="vue"><template>
  <div :my-value="myValue"></div>
</template>

<script>
import { ref } from 'vue';

export default {
  setup() {
    const myValue = ref('');
    return { myValue };
  }
};
</script></code>
Copy after login
<code>console.log(this.myValue); // 输出从setup绑定的值</code>
Copy after login

The above is the detailed content of How to bind data in setup in vue. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
vue
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template