current position:Home>Template rendering and data binding principles of vue2 and vue3

Template rendering and data binding principles of vue2 and vue3

2021-08-27 06:40:27 Glutinous rice Ctrl_ C

Vue Of template Rendering process

Vue It is recommended to use in most cases template To create your HTML. But templates are templates after all , It's not real dom node . From template to reality dom Nodes also need to go through some steps

  1. Compile the template into render function
  2. Mount the instance , According to the root node render Function call , Recursive generation of virtual dom
  3. adopt diff Algorithm comparison virtual dom, Render to reality dom( similar react The virtual DOM Rendering process )
  4. Inside the component data change , Component and subcomponent references data As props Call again render function , Generate virtual dom, Go back to step 3.

The principle of bidirectional data binding

vue2.xx Use in Object.defineProperty() Method through recursive + Traverse the way to achieve data monitoring

1.vue Two way data binding is through The data was hijacked combination Publish and subscribe mode to achieve , That is, data and view synchronization , Data changes , The view changes , View changes , And the data changes ;

2. The core : About VUE Two way data binding , Its core is Object.defineProperty() Method ;

3. Introduce to you Object.defineProperty() Method
(1)Object.defineProperty(obj, prop, descriptor) , There are three parameters in this syntax , Respectively obj ( The object whose properties you want to define ) prop ( Properties to define or modify ) descriptor ( Specific ways to change )
(2) In short , This is how to define a value . When we call, we use the get Method , When we assign a value to this property , It uses the set Method ;

shortcoming :1. Methods listening to arrays cannot trigger Object.defineProperty Methods set operation ( If you want to listen , You need to rewrite the array method ).
2. You have to traverse every attribute of every object , If objects are deeply nested , You need to use recursive calls .

vue3 Mentioned with Proxy Instead of defineProperty, Compared with defineProperty How to hijack object properties ,Proxy It is an interception before the object operation , Returns a proxy object of an operand to indirectly manipulate the object

copyright notice
author[Glutinous rice Ctrl_ C],Please bring the original link to reprint, thank you.

Random recommended