有时候需要监听原生data里面的某个值改变执行相应的函数
方法1:Proxy
一.声明
proxyWatch() {
const me = this;
return new Proxy(this.data,{
set: function( ) {
me.Fn() // 值改变需要执行的func
return true;
}
})
}
二.使用
this.proxyWatch().value= request.xxxx;
该执行更新视图的setData还是要写
this.setData({
value: request.xxxx,
})
方法2 Object.defineProperty
一.声明
proxyWatch() {
const me = this;
let oldvalue = []
Object.defineProperty(
me.data,
'value',
{
get(){
return oldvalue
},
set(newValue) {
oldvalue = newValue ;
me.Fn()
},
enumerable : true,
configurable : true
}
)
},
二.使用
onLoad(){
this.proxyWatch()
}
二者区别:Proxy 可以一次监听多个 ,Object.defineProperty 监听多个需要遍历