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.
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
ref
attribute to the element or component reference bound to a variable in the setup. 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>
2. v-model
v- 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>
3. Custom attributes
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>
<code>console.log(this.myValue); // 输出从setup绑定的值</code>
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!