1. 在 app.js
里了定义一个全局函数,当然也可以单独写一个模版,再通过引入模块的方式来调用
initWatch(_page) {
if (!_page) {
console.error('未检测到Page对象,请将当前page传入该函数');
return false;
}
if (!_page.watch) {
console.error('未检测到Page.watch字段(如果不需要监听,请移除initWatch的调用片段)');
return false;
}
let _dataKey = Object.keys(_page.data);
Object.keys(_page.watch).map((_key) => {
_page.data['__' + _key] = _page.data[_key];
if (_dataKey.includes(_key)) {
Object.defineProperties(_page.data, {
[_key]: {
enumerable: true,
configurable: true,
set: function(value) {
let oldVal = this['__' + _key];
if (value !== oldVal) {
setTimeout(function() {
_page.watch[_key].call(_page, oldVal, value);
}.bind(this), 0)
}
this['__' + _key] = value;
},
get: function() {
return this['__' + _key]
}
}
})
} else {
console.error('监听的属性[' + _key + ']在Page.data中未找到,请检查~')
}
})
}
2. 在具体页面里调用 initWatch
函数,并编写要watch的相关字段
const app = getApp()
Page({
data: {
currYear: ''
},
watch: {
'currYear': function (value) {
console.log('监听数据-currYear', value, this)
}
},
onLoad() {
app.initWatch(this)
}
})
参考链接