Vue data responsive

What is data-driven data and view synchronization? Data binding. Data driven is the biggest characteristic of VUejS. In Vuejs, data-driven means that when data changes, the user interface changes accordingly, and developers do not need to manually modify the DOM

1. Object.defineproperty listens to modify read data

Object.defineproperty (obj, prop, Descriptor) can be passed three values. The effect is that the method directly defines a new property on an Object, or modifies an existing property of an Object, and returns the Object. The first value is passed in the object to be modified the second value is passed in the key to be modified in that object and the third value is an object that has two methods set and GET. Set is what you do when you change the value. Get is what you do when you read the change

1. Responsivity principle

To iterate over incoming data when generating vue instances, use Object.defineProperty to convert these properties to getters/setters. Each Vue instance has a Watcher instance, which records these properties when the instance renders and rerenders when the setter fires.

Disadvantages:

It is impossible to listen to all changes of arrays, add and delete objects, and re-render data. As long as the data of basic data types declared in data, there is basically no data non-response problem. Therefore, it focuses on the data response problem of arrays and objects in VUE, and VUE can detect the modification of object properties. Instead of listening for all changes in the array and new additions and deletions of objects, you can only use the array variation method and $set method.

3. Update the queue asynchronously

Vue updates the DOM asynchronously. Updates are performed synchronously in the main thread. When watcher listens for data changes, it stores the data changes to the asynchronous queue. The task in the asynchronous queue will not be executed until the data changes, that is, the main task, are complete. If you try to manipulate the DOM immediately after updating data in JS, the DOM has not yet been updated; Vue provides the nextTick interface to handle this situation, and its argument is a callback function that will be called after the DOM update is complete.

Why can’t VUE listen for array changes?

Object.defindproperty can implement bidirectional binding, but it still has some disadvantages. It can only hijack the attributes of the Object, so it will deeply traverse the whole Object, no matter how deep the hierarchy is, as long as there are objects nested in the array, you can listen to the data changes of the Object, but not the changes of the array. Proxy doesn’t have this problem and can listen for data changes on the entire object, so vue3.0 uses Proxy instead of definedProperty.