1. Vue bidirectional binding principle

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.

Object. DefineProperty () is used for each vUE attribute as follows:

function defineReactive (obj, key, val) { var dep = new Dep(); Object.defineProperty(obj, key, { get: Function () {// Add the subscriber watcher to the theme object Dep if(dep.target) {// the browser single-threaded feature of JS ensures that this global variable only has the same listener using dep.addSub(dep.target) at the same time; } return val; }, set: function (newVal) { if(newVal === val) return; val = newVal; console.log(val); Dep.notify (); } function observe(obj, obj, obj, obj, obj, obj, obj, obj, obj) vm) { Object.keys(obj).forEach(function(key) { defineReactive(vm, key, obj[key]); })}Copy the code

First we implement data hijacking with Object.defineProperty() for each vue attribute, assigning each attribute a management array DEP of the subscriber collection; V-model will add a subscriber, {{}} will add a subscriber, v-bind will add a subscriber, {{}} will add a subscriber, v-bind will add a subscriber, {{}} will add a subscriber, v-bind will add a subscriber, {{}} will add a subscriber, v-bind will add a listener for input, change the value will assign a value to the attribute, trigger the set method for the attribute, The subscriber array DEP is notified in the set method, and the subscriber array loops through each subscriber’s UPDATE method to update the view.