Vue goes deep into the principle of responsiveness

table of Contents

1. How to track changes:

2. Attention options for detecting changes:

Three, declare the responsive property:

Four, asynchronous update queue:


1. How to track changes:

1. Pass the ordinary JS object into the Vue instance as the data option, and Vue will traverse all the properties of this object. And use Object.defineProperty to convert all these properties into getter/setter .

2. The getter/setter internally allows Vue to track dependencies and notify changes when the property is accessed and modified.

3. Each component instance corresponds to a watcher instance, and the data property "touched" is recorded as a dependency during the component rendering process. The watcher will be notified when the dependent setter is triggered, so that its associated components will be re-rendered.

2. Attention options for detecting changes:

1. Vue cannot detect changes in objects and arrays.

2. Vue does not allow dynamically adding follow-level responsive properties.

But you can use

Vue.set(vm.someObject,"b",2); this.$set(this.someObject,"b",2);

3. Assign multiple new properties to existing objects. Create a new object with the original object and the peoperty of the object to be mixed in.

this.someObject = Object.assign({},this.someObject,{a:1,b:2})

4. Vue cannot detect the changes of the array.

(1) Use the index to set the array value.

vm.items[indexOfItem] = new Value;

(2) Modify the length of the array.

vm.items.length = newLength;

Solve the first type of problem:

vm.set(vm.items,indexOfItem,newValue);

vm.items.splice(infrxOfItem,1,newValue)

Solve the second type of problem:

vm.items.splice(newLength);

Three, declare the responsive property:

 Vue does not allow dynamic addition of root-level response properties. All root-level reactive properties must be declared before the instance is initialized.

Four, asynchronous update queue:

1. Vue is executed asynchronously when updating the DOM.

2. As long as it detects data changes, Vue will open a queue and buffer all data changes that occur in the same event loop.

3. The same watcher is triggered multiple times and will only be pushed into the queue once.

4. Vue internally tries to use native Promise.then, MutationObserver and setImmediate setTimeOut(fn,0) for asynchronous queues;

 


Note: Reference material: Vue official website. 

 

 

 

Guess you like

Origin blog.csdn.net/weixin_43690348/article/details/112831957
Recommended