Usually my study notes are put in the memo and get dusty. Today I have time to sort out the differences in the principles of data binding between vue2 and vue3.
If you sum it up in one sentence, it is that the implementation principle of vue2 relies on Object.defineProperty, while vue3 relies on Proxy.
Object.defineProperty
This method can directly define a new property on an object, or modify an existing property of an object, and return the object. The responsive data officially implemented in this way in vue2
But for this kind of ordinary properties, it is okay. Monitoring of arrays and objects needs to be re-encapsulated, and deep monitoring of complex objects requires constant recursion. Therefore, it has some shortcomings:
1. Deep monitoring requires recursion to the end and requires a large amount of calculation at one time.
2. Unable to monitor new attributes/deleted attributes (vue.set and vue.delete)
Therefore, vue3 uses proxy to implement responsiveness.
Proxy
Can be used to create a proxy for an object to implement interception and customization of basic operations (such as property lookup, assignment, enumeration, function calling, etc.).
Remember to match proxy with reflect. They have a one-to-one relationship.
const proxyData = new Proxy(data, {
get(target, key, receiver) {
// 只处理本身(非原型的)属性
const ownKeys = Reflect.ownKeys(target)
if (ownKeys.includes(key)) {
console.log('get', key) // 监听
}
const result = Reflect.get(target, key, receiver)
return result // 返回结果
},
set(target, key, val, receiver) {
// 重复的数据,不处理
if (val === target[key]) {
return true
}
const result = Reflect.set(target, key, val, receiver)
console.log('set', key, val)
// console.log('result', result) // true
return result // 是否设置成功
},
deleteProperty(target, key) {
const result = Reflect.deleteProperty(target, key)
console.log('delete property', key)
// console.log('result', result) // true
return result // 是否删除成功
}
})
So in comparison, the benefits of proxy:
1. Improved performance. In the past, deep monitoring was required when coming up. Now, monitoring is only performed when a trigger is reached.
2. Can monitor new/deleted attributes
3. Arrays that can be monitored
It can avoid the problem of object.defineProperty, but it is not compatible with all browsers, which is also one of its drawbacks. As for which ones are incompatible, you can go to the can i use website to search for the compatibility of various attribute methods.