The principle of bidirectional binding in VUe2:
Object.defineproperty () method is used to listen the read and write of the attribute in the Object. The get() and set() functions of Object.defineProperty are used to perform additional operations when the attribute is read and write.
Bidirectional binding of different types of data:
1. Basic data types
- Process the data object in vUE to make it responsive
That is, the get() and set() functions of Object.defineProperty are used to intercept operations
Observe () method: Perform a responsive processing principle of traversing a data object. If the data object is null or not an object, no processing or an error is reported, otherwise the defineReactive() method is called.
DefineReactive () : Set the get() and set() methods for each attribute. If get() returns its value, call set() changes the value and triggers the view update.
2. The object
Add another layer of listening to the properties inside the object, up to the base datatype:
And add a layer of listeners when setting object values:
Disadvantages of object bidirectional binding:
When new attributes are added to objects: if they are not first compiled by vUE, they are not added to get, set, and so are not listened to modify. When an Object deletes a property: The get and set functions in object. defineProperty do not listen for changes and are not refreshed
Object bidirectional binding defect, vue2 solution
Delete () this.$delete is an alias of vue.delete. Vue.delete(object, key) When an object deletes an attribute: vue.set () this.$set is an alias of vue.set. Vue.set(object, key, value)
An array of 3.
- Set (vm.items, indexOfItem, newValue); set(vm.items, indexOfItem, newValue)
- Using array methods does not update views. Add view update functionality to the original array methods
Principle of implementation:
Make the array prototype custom, not only to do what the array call method would do, but also to update the view.
Implementation steps:
1. Create an array object, assign it to the array prototype, and get all the array methods on the prototype
2. Use the object. create(its prototype) method to create an array Object with the prototype created in the first step.
3. Rewrite method 7 that can change the original array. The actual method is: for the new array created in step 2, the method that builds the array, the method body to do 1. Call the native array method (that is, call the method on the array object in step 1). Update the view
4. Check in the Observer if it is an array and change its prototype to the one we defined in step 2