To talk about vue’s reactive data principles, you need to understand what the object.defineProperty () interface in javascript can do. In JS, all Object types inherit from the original Object class, except the data of the basic type which is the Object type. Therefore, all Object type data has methods on the Object prototype.
Each property (x) in each object type has four descriptors to describe its configruable, value, enmurable, and writable properties. You can visit MDN to see what each attribute represents.
In addition, JS provides two functions as description properties for each property: get and set.
Get is called when accessing a property. If there is a get function, the property access ignores the value of value and returns the value returned by get.
If there is a set function, it is executed when assigning a value to an attribute. This object is passed in for assignment.
The responsive principle of VUe2 depends on the implementation of this interface
When a VUE component (instance) is instantiated, the data returned from the data function is processed in a reactive manner prior to create. Each property in data is traversed.
/ / pseudo code
for(let item in data){
Object.defineProperty(data,item,{
get(){
dep(); // Collect dependencies here
},
set(val){
update(); // Updates are triggered when data is updateditem = val; }})}Copy the code
For performance reasons, VUe2 does not iterate through the array and cannot monitor the array changes by assigning values to the array using subscripts. But VUe2 intercepts and overwrites the array method to achieve the purpose of responsiveness. One (the split, a push, shift, unshift, reverse). Any of these methods can be called for reactive purposes.
Vue also provides a set interface to dynamically add responsive data to the root node (data).
Set (data,target) calls object.defineProperty (data,target,options) internally to add attributes to the root node. And override the get and set attribute with Object.defineProperty (), and do dependency collection at the same time. Then, the responsive effect of new data is achieved