Vue2 defineProperty newobj is a deep copy of obj. If get returns obj. Name, get will trigger an infinite loop.
let obj ={
name:""
}
let newObj =JSON.parse(JSON.stragify(obj))
Object.defineProperty (obj,"name", {get:function(){
return newobj.name
},
set:function(val){
newobj.name=val
observe()
}
)
function observe () {
//set the operation after updating the new value
}
setTimeout(() = > {
object.name = "vue2"
}, 1000)
Copy the code
Second, vuE3 proxy
Target is your target object, prop is its property, and set has one more value than GET, which is the value to change
let obj ={ name:"" } let newobj = new Proxy (obj,{ get(target,prop){ return target[prop] }, Set (target,prop,value){target[prop] = value observer()}}) function observe () {setTimeout(() => { object.name = "vue2" }, 1000)Copy the code
- advantage: - Listen directly for objects instead of properties - listen directly for changes in arrays - There are 13 ways to intercept - Proxy returns a new object, you can only manipulate the new object to achieve the purpose, Object. DefineProperty can only be modified directly by traversing Object attributes (requiring deep copy modification) - Proxy as the new standard will be heavily targeted by browser vendors for continued performance optimizationCopy the code