vue2 Yes yes Object.definedProperty() To implement array hijacking ,
* When vue After initializing objects on data , You can see that there are get and set method ,get Is a function triggered when reading attribute values ,set Is a function triggered by setting the attribute value . var
Book = {} var name = ''; Object.defineProperty(Book, 'name', { set: function
(value) { name = value; console.log(' You got a book called ' + value); }, get: function () {
return '《' + name + '》' } }) Book.name = 'vue Authoritative guide '; // You got a book called vue Authoritative guide
console.log(Book.name); // 《vue Authoritative guide 》 -- set set up name Triggered when attribute value ,get read name Trigger when value
* Implement simple version of data binding
*
adopt Object.definedProperty() Set a set function , This function is triggered when the data changes , Customize some methods to be updated on the set Function data to update view
* Implementation ideas
Customize the implementation process of bidirectional binding
* First, hijack and monitor the data , Set up a listener Observer, To listen to all properties .-- When attributes change , Tell subscribers Watcher To see if an update is required .
* Subscriber at this time Watcher Corresponding attribute change received , You can execute the corresponding update function to update the view .
* Then we need an instruction parser Compile, Scan and parse each node element , Initialize the related instruction as a subscriber correspondingly Watcher, And replace the template data or bind the corresponding function .
* Subscriber is not a , Is multiple , A message subscriber is required in this case Dep To collect subscribers , And then on the monitor Observer And subscribers Watcher Unified management between .
Observer,Watcher,Dep,Compile Relationship diagram between
Technology