// app.ts
App<IAppOption>({
globalData: {
count:0
},
})
使用 Object.defineProperty 方法进行数据监听
// app.ts
App<IAppOption>({
globalData: {
count:0
},
watch: function (variate: any, method: any) {
var obj = getApp().globalData;
let val = obj[variate];
Object.defineProperty(obj, variate, {
set: function (value) {
val = value;
method(variate, value);
},
get: function () {
return val;
}
})
}
})
在需要监听的组件中注册app().watch 方法
// xxCompinents.ts
Component({
data: {
count: 0
},
lifetimes:{
attached(){
getApp().watch('count', () => {
this.setData({
count: getApp().globalData.count
})
});
}
}
})
在项目中任何页面或组件中,修改count都能被监听到
// xxPage.ts
Page({
handleSetCount(){
getApp().globalData.count = 1
},
handleSetCount(){
console.log(getApp().globalData.count)
}
})
调用 handleSetCount 方法,即可xxComponent 中的count。
可以结合之前的全局登录弹窗使用
微信小程序全局登录弹窗(https://blog.csdn.net/qq_45142260/article/details/128844351#comments_32228729)