微信小程序没有提供类似vue中watch类似的监听属性,如果我们想用,就得自己写一个,直接上代码。
注意:vue中的watch监听属性滥用会造成性能问题,这里自定义的watch也是一样的,要适度使用。
watch.js
const observe = (obj, key, watchFun, deep, page) => {
let val = obj[key];
if (val != null && typeof val === "object" && deep) {
Object.keys(val).forEach((item) => {
observe(val, item, watchFun, deep, page);
});
}
Object.defineProperty(obj, key, {
configurable: true,
enumerable: true,
set: (value) => {
watchFun.call(page, value, val);
val = value;
if (deep) {
observe(obj, key, watchFun, deep, page);
}
},
get: () => {
return val;
}
});
}
const setWatcher = (page) => {
let data = page.data;
let watch = page.watch;
Object.keys(watch).forEach((item) => {
let targetData = data;
let keys = item.split(".");
for (let i = 0; i < keys.length - 1; i++) {
targetData = targetData[keys[i]];
}
let targetKey = keys[keys.length - 1];
let watchFun = watch[item].handler || watch[item];
let deep = watch[item].deep;
observe(targetData, targetKey, watchFun, deep, page);
});
}
module.exports = {
setWatcher
};
使用示例:
// 引入自定义监听属性
import watch from '../../core/js/watch';//这里的路劲取决于你自己的watch.js文件的存放路径
Page({
data: {
name: "测试watch"
},
onLoad() {
watch.setWatcher(this);
let that = this;
setTimeout(function () {
that.data.name = "测试watch变化了"
}, 5000)
},
watch: {
name: function(newVal, oldVal) {
//这里的this和onLoad里的this指向一样
console.log(newVal, oldVal);
}
}
});