One, what is a V-Model
V-model is a two-way binding instruction of VUE, which can synchronize the input value of the control on the page to the data property of the related binding, and also update the value of the input control on the page when the data binding property is updated.
Second, why use v-Model
As a two-way binding instruction, V-Model is also one of the two core functions of VUE, which is very convenient to use and improves the efficiency of front-end development. In the View layer, the Model layer needs to interact with each other using the V-Model.
Three, the principle of V-Model is briefly described
V-model mainly provides two functions: The input value of view layer affects the attribute value of data, and the change of data attribute value will update the value change of VIEW layer. The following uses the INPUT control binding V-Model as an example.
<! DOCTYPE html> <html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<div id="app">
<p>{{name}}</p>
<input type="text" v-model="name" />
</div>
</body>
</html>
Copy the code
3.1 Input Update data after input value
First, during page initialization, the VUE compiler compiles the HTML template file, traversing the DOM elements on the page to generate a virtual DOM tree. Recursively traverses each node of the virtual DOM. When it matches that it is an element rather than plain text, it continues through each attribute. If traversed through the V-model property, an input event is added to the node to update the corresponding property value of data in the VUE instance when listening for input values from the page.
// If node is the input node iterated over, node.adDeventListener ("input".function(e){
vm.name=e.target.value;
})
Copy the code
3.2 Update the input value after assigning the data property
Similarly, when initializing the Vue instance, each attribute of data is recursively traversed, and the get and set methods of each attribute are monitored through defineProperty, so that once a attribute is reassigned, the corresponding page control can be monitored for changes.
Object.defineProperty(data,"name", {get() {return data["name"];
},
set(newVal){
let val=data["name"];
if (val===newVal){
return;
}
data["name"]=newVal; Node. value=newVal; // If node is the corresponding input node, node.value=newVal; }})Copy the code
Four,
The core is that, on the one hand, the Modal layer hijacks each attribute via defineProperty, and once changes are monitored updates through the associated page element. On the other hand, by compiling the template file, bind the input event to the V-model of the control, so that the page input can update the relevant data attribute value in real time.