-
Instead of using JS or jquery to change the DOM directly, VUE uses v-Model to achieve bidirectional binding of data, which automatically selects the correct method to update elements according to the control type.
-
V-model is the two-way binding instruction of VUE, which can synchronize the input value of the control on the page to the relevant bound data property, and also update the value of the input control on the page when the data binding property is updated
The official document explains that the V-Model is just a syntactic sugar, but the real implementation depends on
- V-bind: binds responsive data
- Trigger input events and pass data (core and focus)
The following code
<input v-model="txt">
Copy the code
Essentially,
<input :value="txt" @input="txt = $event.target.value">
Copy the code
Explanation:
When you initialize the vue instance, you recursively iterate over each attribute of the data and listen for the GET and set methods of each attribute via defineProperty. In this way, once a attribute is reassigned, you can listen for changes and manipulate the corresponding page control
Look at the code below:
Object.defineProperty(data,"name", {get(){
return data["name"];
},
set(newVal){
let val=data["name"];
if (val===newVal){
return;
}
data["name"]=newVal;
// Listen for a change in the value of the attribute, if node is its input nodenode.value=newVal; }})Copy the code
conclusion
On the one hand, the modal layer hijks each attribute through the object.defineProperty, updating it through the associated page element once the change is heard. On the other hand, by compiling the template file, the v-Model of the control is bound to the input event, so that the page input can update the relevant data property value in real time
Object. DefineProperty is used to control some special operations on an Object property, such as read and write rights and whether it can be enumerated or not. Here we mainly study its corresponding two description properties get and set. Get is triggered by reading the value of name, and set is triggered by setting the value of name
supplement
V-model modifiers:.lazy,.trim, and.number
- lazy: After each input event is triggered, the value of the input box is synchronized with the data and addedlazyModifier to use the change event for synchronization
<input v-model.lazy="msg">
Copy the code
- trim: Removes the Spaces at the beginning and end of the string
<input v-model.trim="msg">
Copy the code
- number: Converts data to a value type
<input v-model.number="msg">
Copy the code