遇到的问题
两个页面同时监听store中的同一个值ConnectStatus,A页面中获取到ConnectStatus值为1时跳转index页面,B页面中获取到ConnectStatus值不为1时跳转first页面。现在是A页面ConnectStatus为1时跳转的是first页面。
解决方案
进入A页面,A页面监听ConnectStatus,B页面不监听;进入B页面,B页面监听ConnectStatus,A页面不监听。
解决方法
1.App.vue:
globalData: {
wather:''
},
2.页面(A、B页面都需要写):
computed: {
connectStatus() {
return this.state.ConnectStatus
}
},
onShow() {
this.$createWatcher('changeAuth')
},
onBackPress() {
console.log('有没有被销毁')
this.$removeWatcher()
}, //返回没有被销毁加的onBackPress(),跳转进入onHide()
onHide() {
this.$removeWatcher()
},
methods:{
$createWatcher(name) {
getApp().globalData.watcher = this.$watch(
'connectStatus',
(newVal, oldVal) => {
this[name](this.connectStatus)
}, {
deep: true,
immediate: true
})
},
$removeWatcher() {
// 检查是否有已存在的观察者
if (getApp().globalData.watcher) {
// 调用观察者返回的取消函数,即取消对特定属性的监听
getApp().globalData.watcher()
console.log('Watch 移除成功!')
} else {
console.log('没有观察者可移除!')
}
},
changeAuth(newVal) {
if (newVal === 1) {
this.connect();//编辑自己的代码
}
},
}