小程序项目开发想实现全局监听globalData数据变化,可参考数据劫持的实现方式,代码如下:
app.js
globalData: {
msgTotal: ''
},
// 使用数据劫持模式监听数据变化
observe(obj, key, watch, that) {
let val = obj[key];
Object.defineProperty(obj, key, {
configurable: true,
enumerable: true,
set: function (value) {
watch(val, value, that);
val = value;
},
get: function () {
return val;
}
})
}
页面赋值msgTotal
const app = getApp()
Page({
setMsgTotal() {
app.globalData.msgTotal = res.data.total
}
})
组件内监听msgTotal
const app = getApp()
methods: {
watch (oldVal, newVal, that) {
that.setData({
msgTotal: newVal
})
}
},
// 组件生命周期
lifetimes: {
// 组件进入页面节点树执行
attached() {
app.observe(app.globalData, "msgTotal", this.watch, this);
}
}
小程序页面监听msgTotal
const app = getApp()
Page({
onReady() {
app.observe(app.globalData, "msgTotal", this.watch, this);
},
watch (oldVal, newVal, that) {
that.setData({
msgTotal: newVal
})
}
})