JavaScript is restricted modern, Vue unable to detect the object properties added or deleted.
Since the Vue will be converted to perform property getter / setter at initialization instance, the property must be present in order for the data subject Vue responsive to convert it into a.
But Vue offers
Vue.set (object, propertyName, value) / vm.$set (object, propertyName, value)
Add to realize responsive property to the object, the framework itself how it is to achieve it?
We view the corresponding Vue Source:
vue/src/core/instance/index.js
Export function SET (target: the Array <the any> | Object, Key: the any, Val: the any): the any { // array of target IF (Array.isArray (target) && isValidArrayIndex (Key)) { // the length of the array is modified avoid index> length of the array results in splcie () performs error target.length = Math.max (target.length, Key) // use the array splice variant method of triggering responsive target.splice (Key,. 1 , Val) return Val } // Key already exists, directly modify the attribute value IF (Key in target &&! (Key in Object.prototype)) { target [Key] = Val return Val } OB const = (target: the any) .__ ob__ // target responsive data itself is not directly assigned IF (! OB) { target [Key] = Val return Val } // attributes for responsive treatment defineReactive (ob.value , Key, Val) ob.dep.notify () return Val }
We read the source code can be seen above, vm $ set to achieve the principle is:
- If the target is an array, the array directly splice method of triggering a corresponding formula ;
- If the target object, will first interpretation property exists, whether the object is responsive , and ultimately if you want to attribute responsive handling, it is responsive process by calling defineReactive method (defineReactive is to Vue when the object is initialized to the object Object.defineProperty dynamically add properties using getter and setter methods of function calls)