Two-way data binding
Personal notes, please forgive me for any mistakes.
The approach of Vue.js is to use the data hijacking plus publisher subscription mode, through object.defineproperty() to hijack the getter and setter methods of each property, the setter monitors the value change, and the getter returns the changed value. When the data changes, object The set method of .property() monitors the data, returns the modified data through the get method, and notifies the subscriber (watcher) through the Dep.notify method, allowing the subscriber to attack the view to update the data.
The simulated vue code mainly implements three things
Implement a command parser Complie
Implement a data listener Observer
Implement a Watcher to update the view
Implement a proxy proxy
Achieve complie
Prepare the template
In the Mvue.js file,
add document before the querySelector above.
You can see that we have bound the template and the Mvue class.
Then you need to traverse the nodes to replace data
Each replacement monitoring will cause continuous destruction and reflow of the page. At this time, with the help of the document fragment object, it is put into memory to reduce redrawing and reflow.
Use for of to traverse all the nodes of the template,
and then put them into the document fragment clock one by one
You can see that the node on the left is already in the document fragment object.
Then append the node to the element to be inserted, that is, the app will
then be compiled before the template is parsed.
So let's not append yet. Compile before appending.
All element nodes are taken out.
Note that we are only traversing the first layer, so we have to judge
Some templates have instructions such as v-mode, v-html, v-text, and the corresponding operations can be realized through the judgment of the instructions.
First get the attributes on this node, there are instructions in
it. Get it through node.attributes.
By forcing it into an array and traversing its value,
we only need the attributes at the beginning of v-, so
we need to make a judgment through the difference of dirname. Different judgments require the use of strategic models
Strategy mode ()
Corresponding operations can be made by defining attributes: methods in the object.
Then you will first load the template into the app.
You can see that the function of template compilation is realized.
There are also some values that are bound to AA
and remember to delete the attribute after updating the data.
Summary:
The compiled text nodes for text nodes are these { {}}
. . . arg is an array, the first value is to remove
the data of { {}},
##Next is the binding event
Not pointing to window
Process v-bind
Processing syntactic sugar
At this point, all compiling and parsing functions have been implemented.