Vue. js uses data hijacking combined with publiser-subscriber mode. It hijacks the setter and getter of each attribute through Object.defineProperty(), releases messages to subscribers when data changes, and triggers corresponding listening callback. Let’s start with object.defineProperty () :

var obj = {}; Object.defineproperty (obj, 'name', {get: function() {console.log(' I got it ') return val; }, set: function (newVal) {console.log(' I was set ')}}) obj.name = 'fei'; Var val = obj.name; var val = obj.name; // When obj's name property is obtained, the get method is triggeredCopy the code

We already know that Vue uses data hijacking to bind data. The core method is to hijacking attributes via Object.defineProperty(). When setting or fetching, we can use get or set methods if other triggering functions, This method is undoubtedly one of the most important and basic contents in this article.

How does Vue implement bidirectional data binding?

Vue two-way data binding mainly refers to: data changes update view, view changes update data, as shown in the following figure:

That is:

  • When the content of the input box changes, the Data in Data changes synchronously. View => Data changes.
  • As the Data in Data changes, the content of the text node changes synchronously. Data => View changes.

Among them, View changes update Data, can be achieved through the way of event listening, so Vue two-way Data binding work is mainly how to update the View according to Data changes.

Vue implements bidirectional data binding through the following four steps:

Implement a listener Observer that iterates over data objects, including properties of child property objects, adding setters and getters to all properties using Object.defineProperty(). So, if you assign a value to this object, it will trigger the setter, so you can listen for changes in the data.

Implement a parser Compile: parse Vue template instructions, replace variables in the template with data, and then initialize render page view, and bind the corresponding node of each instruction to update function, add subscribers to listen to the data, once the data changes, receive notification, call update function for data update.

Implement a subscriber Watcher: The Watcher subscriber acts as a bridge between the Observer and Compile. Its main task is to subscribe to the message of the change of attribute value in the Observer. When the message of the change of attribute value is received, the corresponding update function in the parser Compile is triggered.

Implement a subscriber Dep: The subscriber uses a published-subscribe design pattern to collect subscriber Watcher and manage listener Observer and subscriber Watcher uniformly.