在vue2中实现数据双向绑定用的是Object.defineProperty
<script>
let m = {
a:1,
b:2,
arr:['a','b','c']
}
// Object.defineProperty
let o = {}
Object.keys(m).forEach(key=>{
Object.defineProperty(o,key,{
get(){
return m[key]
},
set(){
console.log('修改了')
}
})
})
o.arr[0] = 'XXXX'
console.log(o)
</script>
vue3中使用Proxy实现数据双向绑定
<script>
let m = {
a:1,
b:2,
arr:['a','b','c']
}
// start
// proxy
let o = new Proxy(m,{
// get(target,key){
// return target[key]
// },
// set(){
// console.log('修改了')
// }
// start
// 解析任何数据类型
get(target,key,receiver){
return Reflect.get(target,key,receiver)
},
set(target,key,value,receiver){
return Reflect.set(target,key,value,receiver)
}
})
o.arr[0] = 'pppp'
console.log(o)
// End
</script>