小程序实现多页面同时监听globalData值变化,实现小程序全局数据监听
app.js 目录下
1.利用Object.defineProperty方法执行页面的回调函数
2.多页面同时监听 -> 例: 监听isLogin 则在watchMethods中开辟watchMethods.isLogin = [],然后存放监听的方法。当isLogin变化时遍历执行watchMethods.isLogin中所有的方法,即watchMethods.isLogin.map( item => item( xxx))
App({
globalData: {
isLogin: false,
},
watchMethods: {},
watch(param) {
const that = this
const obj = this.globalData
for(let key in param) {
if(!this.watchMethods[key]){
this.watchMethods[key] = []
}
const method = param[key]
this.watchMethods[key].push(method)
Object.defineProperty(obj, key, {
set(val) {
const methods = that.watchMethods[key]
methods.map(item => item(val))
}
})
}
},
page/index/index.js目录
onLoad() {
this.watch()
},
watch() {
app.watch({
isLogin(val){
console.log('首页:'+val)
}
})
},
page/category目录
<!-- category.wxml -->
<wxs module="wxs" src="./data.wxs"></wxs>
<view class="main">品类页面</view>
<view class="main">{{wxs.color}}</view>
<button bindtap="doLogin">登陆</button>
//category.js
let app = getApp()
Page({
onLoad() {
this.watch()
},
doLogin() {
app.globalData.isLogin = !app.globalData.isLogin
},
watch() {
app.watch({
isLogin(val){
console.log('品类:'+val)
}
})
},
})