Please answer the principle of two-way data binding like this

foreword

Two-way data binding is an important principle of Vue, and it is also a question that almost must be asked in the interview process. Understanding this principle is beneficial to both our technical improvement and the interview. Let us Let's solve this problem together~

What is the responsibility of each module in two-way data binding?

new view

The operation of new Vue mainly calls the data hijacking Observe method and the function Compile of template compilation.

Observe function

The Observer function will recursively traverse all the properties of the incoming object, and use Object.defineProperty to convert all these properties into getters/setters. Once the monitored property changes, the Dep class is notified.

Dep class

The Dep class is responsible for collecting each watcher and notifying each collected watcher when the Observer listens for property changes.

Watcher class

Watcher is a bridge between Observe and Compile. Watcher will add itself to the dep class when it is instantiated, and provide an update method. Once the property changes, the dep class will use this method to trigger the callback function in Compile. to render data.

Compile function

The main job of the Compile function is to replace the variables in the template with data, then render the page view, and bind an update function to each node, create subscribers, and update the view when the data changes, because when traversing The DOM will be manipulated multiple times. In order to improve efficiency, the root node will be converted into a document fragment fragment for offline DOM operation. After the parsing is completed, the fragment will be added to the real DOM.

Two-way data binding principle flow chart

image.png

The difference between Vue2 and Vue3 reactive principle

  1. Vue2 uses Object.defineProperty() to implement the responsive principle, while Vue3 uses Proxy() to implement.
  2. When facing object nesting, both Vue2 and Vue3 need to recurse, but Vue2 is recursive to all properties, while Vue3 is recursive on demand. If the properties of internal objects are not used, do not recurse, and the performance is better .
  3. Properties that do not exist in objects in Vue2 cannot be intercepted, but Vue3 can.

Why does Vue3 deprecate ObjectdefineProperty and choose Proxy

  1. Object.defineProperty cannot monitor the change of the array subscript, so adding elements through the array subscript cannot respond in real time.
  2. Proxy can not only proxy objects, but also proxy arrays, and can proxy dynamically added properties.
  3. Object.defineProperty cannot monitor data structures such as Map and Set newly generated by ES6.

Summarize

When answering questions about two-way data binding, you can combine the above flow chart to introduce the main work of each node, and explain the process clearly.

Guess you like

Origin blog.csdn.net/sinat_41696687/article/details/123362327