background
A few days ago, I was asked about the difference between vuE2 and VUE3 two-way binding. I always feel very familiar with it, but I can’t express it in words. So call, hope through this article sort out.
vue2
1. Object.definedProperty()
Object.definedproperty () is an ES5 property that hijacks reading and writing data through get() and set() methods.
2. Iterate over data
Each component has a data option, and when the component is rendered, the data is traversed and turned into getters/setters with object.defineProperty. The attribute added after data cannot observe
- Data There are objects in the data, traversal recursion
- Data contains an array. If the elements of the array are objects, repeat 1. If not, special treatment is performed
3. Extra processing is required for arrays
Vue cannot detect two changes
- Using the index to change directly, ES6 changes when the array instance method
- Changing the array length
Object.definedproperty () doesn’t allow you to listen directly to an array. It only accepts seven methods that essentially override the source code to trigger updates. These two implementations are less cost-effective.
push() pop() shift() unshift() splice() splice() sort() reverse()
Copy the code
Corresponding solutions
- Vue.set (this.arr, index, newValue) or deep copy the newValue overwrite
- this.arr.splice(newLength)
Just to be clear: if the watcher instance cannot detect the change, the data on the page is still detectable. However, in order to avoid inconsistency between the Watcher instance and the page, avoid using undetectable changes and use corresponding solutions
vue3
1. Proxy()
Proxy() is an ES6 constructor that intercepts external reads and writes to the target object. No traversal is required
2. ref() reactive()
Ref () reactive() can be added at any time
3. No additional processing is required for arrays
Proxy() can listen on arrays
conclusion
-
The difference between vuE2 and VUE3 bidirectional binding is that they use different methods to listen to data, resulting in different listening modes and listening characteristics.
-
In VUE2, the method that es5 array method changes the original array is processed, but the method that ES6 array method changes the original array is not processed.