微信小程序实现watch监听数值改变的效果
前言
- 需要用到Javascript中的Object.defineProperty()方法,实现劫持对象的get/set指令,从而监听到对象的赋值(调用setter),达到监听数值改变效果
示例
监听变量方法:
function watchData(pageData, key, fn) {
var oldVal = pageData[key];
Object.defineProperty(pageData, key, {
configurable: true,
enumerable: true,
get: function () {
return oldVal ;
},
set: function (newVal) {
if (newVal === oldVal) return;
fn && fn(newVal);
oldVal = newVal;
},
});
fn && fn(oldVal);
}
监听 scrollTop 的值的变化,根据 scrollTop 的值调整导航栏的样式:
onShow: function (option) {
const that = this;
this.watchData('scrollTop', val => {
if (scrollTop > 200) {
that.setData({navBarStyle: 'mimi'});
} else {
that.setData({navBarStyle: 'default'});
}
});
}
参考
https://blog.csdn.net/weixin_37680520/article/details/105875333
https://blog.csdn.net/Derrrrrd/article/details/124902590
https://blog.csdn.net/y13103192727/article/details/123397219