v-model is used for two-way binding of form data. In fact, it is a syntactic sugar. Two operations are done behind this:
1. v-bind binds a value attribute
2. v-on instruction binds input to the current element Event
A custom component using v-model should have the following operations:
- Receive a value prop
- Trigger the input event and pass in the new value
In the native form element:
<input v-model="inputValue">
Equivalent to
<input v-bind:value="inputValue" v-on:input="inputValue = $event.target.value">
In custom component
<my-component v-model="inputValue"></my-component>
Equivalent to
<my-component v-bind:value="inputValue" v-on:input="inputValue = argument[0]"></my-component>
At this time, the value accepted by inputValue is the first parameter of the callback function of the input event, so in order to implement data binding in a custom component, you also need $emit to trigger the input event.
this.$emit('input', value)
Summary: v-model is essentially a syntactic sugar. The following code <input v-model="message">
is essentially <input :value="message" @input="message = $event.target.value">
, where @input is <input>
a listener for input events, :value="message"
which puts the data in the listener event into input. V-model can not only assign values to the input, but also get the data in the input, and the data acquisition is real-time, because @input is used to monitor the input box in syntactic sugar.