Analysis of vue Data Bidirectional Binding Principle (get set)
- 2021-07-26 06:52:34
- OfStack
Front-end data bidirectional binding refers to the relationship between view (view) and model (data); view layer is the information presented to the user on the page, and model layer 1 generally refers to the data returned from the background through http request. view to model bindings are all operated through event callback functions, and model to view bindings have several methods.
The framework of mv* mode, such as angular, react and vue, all realize data bidirectional binding. angular is to determine which data has changed through dirty check, that is, the comparison of new and old data, so as to update it to view; vue is implemented by setting get and set functions of data, which is superior to angular in performance.
The following code is a simple example of defining data get and set methods. set and get methods are called when data changes and accesses respectively, and can listen for data changes:
// Constructor for data binding
function Observer(data) {
this.data = data;
for(var key in data) {
if(data.hasOwnProperty(key)) {
var val = data[key];
if(typeof data[key] === "object"){
// If the value is not of the original type, recursion continues
new Observer(val);
}else {
this.convert(key, val);
}
}
}
}
// Definition set And get Function
Observer.prototype.convert = function(key, val) {
Object.defineProperty(this.data, key, {
enumerable: true,
confingurable: true,
get: function() {
console.log(key + " Be visited ");
return val;
},
set: function(newVal) {
console.log(key + " Has been set to a new value " + newVal);
val = newVal;
}
});
}
var app = new Observer({name: "xieshuai", age: 24, address: {city: "shenzheng"}});
app.data.name; // name Be visited
app.data.age = 18; // age Has been set to a new value 18
Object. defineProperty, a new method for ES 6, allows you to customize getter and setter functions.
The above code is just a simple example and does not deal with arrays; However, this is the core of vue's bidirectional data binding.
This is the end of this article. If there are any mistakes in this article, I hope to correct it.