There are watch monitors in the vue project, and there are also places that need to be monitored during the WeChat development process. To prevent multiple calls from multiple pages, write the watch method in app.js
// 设置监听器
watch: function (ctx, obj) {
Object.keys(obj).forEach(key => {
this.observer(ctx.data, key, ctx.data[key], function (value) {
obj[key].call(ctx, value)
})
})
},
// 监听属性,并执行监听函数
observer: function (data, key, val, fn) {
Object.defineProperty(data, key, {
configurable: true,
enumerable: true,
get: function () {
return val
},
set: function (newVal) {
if (newVal === val) return
fn && fn(newVal)
val = newVal
},
})
},
Same level as onLaunch() {}
During the use of the page, mount it to the onLoad() position
// 调用监听器,监听数据变化
app.watch(this, {
checkNum: function (newVal) {
console.log(newVal,"监听到了")
}
})
Whether to enable deep monitoring is the same as VUE
app.watch(this, {
checkNum: function (newVal) {
console.log(newVal,"监听到了")
},
immediate: true
})