SoFunction
Updated on 2025-04-09

The principle analysis of vue data bidirectional binding (get & set)

The bidirectional binding of the front-end data refers to the relationship between the view (view) and the model (data); the view layer is the information displayed to the user on the page, and the model layer generally refers to the data returned from the background through http request. The binding of view to model is operated through event callback functions. There are many ways to bind model to view.

The frameworks of mv* modes such as angular, react, vue and other mv* modes all implement bidirectional data binding; angular determines which data has changed through dirty checking, that is, the comparison of new and old data, and updates it to the view; vue is achieved by setting the get and set functions of the data, which is better than angular in performance.

The following code is a simple example of defining data get and set methods. The set and get methods are called when data changes and accesses, respectively, and can monitor data changes:

// Data binding constructorfunction Observer(data) {
  = data;

 for(var key in data) {
  if((key)) {
   var val = data[key];
   if(typeof data[key] === "object"){
    // If the value is not primitive, continue to recurse    new Observer(val);
   }else {
    (key, val);
   }
  }
 }
}
// Define set and get functions = function(key, val) {
 (, key, {
  enumerable: true,
  confingurable: true,
  get: function() {
   (key + "Accessed");
   return val;
  },
  set: function(newVal) {
   (key + "New value has been set" + newVal);
   val = newVal;
  }
 });
}
var app = new Observer({name: "xieshuai", age: 24, address: {city: "shenzheng"}});

;  // name has been accessed = 18; // The new value of age is set to 18

, This is a new method added by ES6. Through this method, you can customize getter and setter functions.

The above code is just a simple example and does not handle arrays; however, this is the core of vue's implementation of two-way data binding.

This article ends here. If there is anything wrong in the article, I hope to correct it.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.