1. Usage of v-model
We all know the usage of v-model. Form controls use v-model to bind a value in data to achieve two-way binding:
<input type="text" v-model="val" />
data(){
return {
val: 0
}
}
2. What is v-model
It is actually one , which is also clearly stated 语法糖
on the vue official website .
For <input type="text"/>
example, it is actually shorthand for :value
(v-bind:value) and @input
(v-on:input). The two-way binding function of the following two <input />
components is the same:
<input v-model="value" />
<input v-on:input="value = $event.target.value" v-bind:value="value" />
<script>
...
data(){
return {
value: ''
}
}
</script>
It's just that the input control below assigns the value bound to the current input element to the variable value in data in the input event;
3. How does it know what type of value is tied to different forms?
There are various types of forms, such as <input>
, <textarea>
, <select>
and so on. The attributes and events bound to the v-model directive are also different.
Elements such as <input>
text and textarea use value
attributes and input
events;
<checkbox>
And <radio/>
such check/single-select elements use checked
attributes and change
events;
<select />
used value
and change事件
;
4. How to bind values using the v-model directive on our custom components
In fact, knowing that v-model is an abbreviation :value
for @input
events, you can basically use v-model instructions on custom components. Now let's see how it is implemented, taking a simple custom input box as an example:
Look at the code first:
- Subassembly:
<template>
<div class="my-input">
<!-- 其他html代码。。。 -->
<input type="text" v-bind:value="value" v-on:input="inputFn" />
</div>
</template>
<script>
export default {
props: ["value"],
data() {
return {
v: "",
};
},
methods: {
inputFn(e) {
this.$emit("input", e.target.value);
},
},
};
</script>
- parent component:
<template>
<div class="home">
<MyInput v-model="tv" />
<!-- <MyInput :value="tv" @input="tv = $event.target.value" /> -->
</div>
</template>
<script>
import MyInput from "../components/MyInput.vue";
export default {
name: "HomeView",
components: {
MyInput },
data() {
return {
tv: 0,
};
},
};
</script>
It can be seen that the input element of the child component is bound with :value
and @input
, @input
when the current <input />
input box is target.value
passed $emit
, the value of the input box is passed to @input
the event of the parent component, and the event of the parent component @input
assigns the passed value to the current The tv variable bound by the custom component.
Therefore, v-model
the tv variable bound by the parent component using the instruction can also be written as the line commented above: use @input
and :value
separate binding events and variables.
In the same way, since v-model will automatically bind different properties and event characteristics according to the type of the current form, you can implement custom check, radio, selector and other components