Vuex组件通信优化:router页面跳转导致watcher不能监听数据变化

本文优化至:http://www.appblog.cn/2018/07/10/Vuex获取this对象及深度state监测/

问题暴露

当httpCode为403未授权时,页面将立即路由跳转至登录页面,导致组件销毁,原页面无法监听状态数据变化,即user_update_watcher无法观察user_update变化,userUpdateWatcher不回调。

1
2
3
4
5
6
7
8
9
COMMON_USER_UPDATE_CALLBACK: (state, response) => {
...
if (httpCode === 403) {
Vue.set(state.user_update, 'success', false)
context.$router.push({path: '/login?page=user_update'})
return
}
...
}

改进方案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
computed: mapState({
user_update_watcher: state => state.account.user_update
}),
watch: {
user_update_watcher: {
handler: 'userUpdateWatcher',
deep: true
}
},
methods: {
userUpdate () {
var params = {}
params.localMsg = {'msg_server_busy': '系统繁忙,请稍后再试!'}
this.$dialog.loading.open('请稍候')
this.$store.dispatch('userUpdate', {'context': this, 'userId': this.userId, 'params': params})
},
userUpdateWatcher (val, oldVal) {
this.$dialog.loading.close()
switch (val.state) {
case 'un_auth':
this.$router.push({path: '/login?page=user_update'})
return
case 'failure':
case 'error':
default:
return
case 'success':
break
}
console.log(val.data)
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
export default {
state: {
user_update: {
'data': null,
'state': '',
'timestamp': 0
}
},
mutations: {
COMMON_USER_UPDATE_CALLBACK: (state, response) => {
Vue.set(state.user_update, 'timestamp', new Date().getTime())
let context = response.context
let httpCode = response.httpCode
if (httpCode === 403) {
Vue.set(state.user_update, 'state', 'un_auth')
return
}
if (httpCode !== 200) {
Vue.set(state.user_update, 'state', 'failure')
context.$dialog.alert({mes: response.localMsg.msg_server_busy, btn_mes: '确认'})
return
}
let code = response.data.code
if (code !== 0) {
Vue.set(state.user_update, 'data', null)
Vue.set(state.user_update, 'state', 'error')
context.$dialog.alert({mes: response.data.error.errMsg, btn_mes: '确认'})
return
}
Vue.set(state.user_update, 'data', response.data.data)
Vue.set(state.user_update, 'state', 'success')
}
},
actions: {
userUpdate ({ commit }, object) {
// 更新用户信息
api.user_update(object.userId, object.params).then((response) => {
commit(types.COMMON_USER_UPDATE_CALLBACK, {'context': object.context, 'httpCode': response.status, 'data': response.data})
}).catch((response) => {
commit(types.COMMON_USER_UPDATE_CALLBACK, {'context': object.context, 'httpCode': response.status, 'data': response.data, 'localMsg': object.params.localMsg})
})
}
}
}

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :