1 – Proxy
const o = { a: 1 }
const proxy = new Proxy(o, {
get(target, key, receiver) {
console.info('get')
// return target[key]
return Reflect.get(target, key, receiver)
},
set(target, key, value, receiver) {
console.info('set')
target[key] = value
// return true // set Returns true to indicate that the assignment is successful. Otherwise, an error will be reported
return Reflect.set(target, key, value, receiver)
}
})
proxy.b = 2 // Proxy can listen for new attributes
Copy the code
2 – Object.defineProperty
const o = { a: 1 }
const defineReactive = (target, key, midValue, configurable = true, enumerable = true) = > {
Object.defineProperty(o, 'a', {
configurable,
enumerable,
get() {
console.info('get:' + midValue)
return midValue
},
set(value) {
console.info('set:' + value)
midValue = value
}
})
}
defineReactive(o, 'a', o['a'])
Copy the code
Difference between 3-proxy and defineProperty
1. Return true in the set method of proxy; otherwise, an error will be reported
DefineProperty intercepts the original object and only needs to access or modify the original object to trigger get and set methods.
Proxy proxies the original object. You need to access or change the object to trigger methods such as GET and set
DefineProperty’s get method has no arguments and needs a midValue to record the new value changed when set is triggered
Proxy monitors objects, and the get method has parameters target and key (set also has parameters). It can directly obtain the accessed value and return it
4, proxy in addition to get and set, there are other interception methods, such as listening to the array, listening to the object attributes of the new, delete, a total of 13.
5. When new attributes are added to the object, proxy can listen to the new attributes of the object.
DefineProperty can’t listen for new attributes, need to listen manually ($set method in Vue2. X, deprecated in 3.0)
4 – advantages of Vue3.0 using Proxy
① In ve2. X, new attributes on objects do not trigger view updates. Because Object.defineProperty cannot listen for the new attribute, you need to manually intercept the listener using the $set method provided by Vue (this attribute will be intercepted via Object.defineProperty)
<div>{{ obj }}</div>
export default {
data() {
return {
obj: {
name: 'xhl'}}},mounted() {
// this.obj.age = 24 // Views will not be updated
this.$set(this.obj, 'age'.24) / /)}},Copy the code
The $set method was abolished in Vue3.0 because Proxy can listen for new attributes on objects