What is the principle of set and $set in Vue and how is it implemented?

principle, realize
principle, realize

Apr.12,2021

as shown in the following figure, first make a judgment that target is not data of type undefined, null, string, number, symbol, and boolean.

1. If target is an array, change the length of the array according to the key value and the length of the array (take the larger one), and then directly use the splice function to modify the array. Although vue does not listen for array changes, it listens for the push,pop,shift,unshift,splice,sort,reverse function of the array, so you can also use splice to update dom

.

2. If target is an object and key is an existing private property of the object, then you can assign the value directly, because the key must be a monitored

.

3. If the key does not currently exist in the object, it will be assigned and listened. The judgment of ob is omitted here, so what is ob? the data initialized in vue (such as the data in data) will be monitored during page initialization, and the listening attributes will be bound to the _ _ ob__ attribute. Here is to determine whether the data has been monitored. If the data is not monitored, then by default you do not want to listen to the data, so assign the value directly and return

set

finally, $set is set

Vue.prototype.$set = set;
Menu