問(wèn)題
在vue組件內(nèi) 通過(guò)commit 更新 vuex modules state 數(shù)據(jù)(obj),vue組件通過(guò)computed mapState獲取不到最新的數(shù)據(jù)
//vuex
//項(xiàng)目初始化會(huì)設(shè)置state中obj為:
/* {
a: {
aa: '000',
bb: '222'
}
}*/
state: {
obj:{}
}
mutations: {
setObj(state, obj = {}) {
state.obj = Object.assign(state.obj, obj);
}
}
//vue
<template>
<div>
//頁(yè)面初始化展示000,調(diào)用setNewData后,展示依舊是000
{{ aa }}
</div>
</template>
computed: {
...mapState({
aa: state => state.common.obj.a.aa
})
},
methods: {
setNewData(){
let obj = {
a: {
aa: '111',
bb: '222'
}
}
this.$store.commit('common/setObj', {
obj: obj
});
}
}
解決
data(){
return {
newAa: {},
unsubscribe: null
}
},
created() {
//這個(gè)aa就是computed里的
//這里也可以直接改寫成 this.newAa = this.$store.state.common.obj.a.aa;
//主要是涉及對(duì)源代碼修改的大小程度
this.newAa = this.aa;
//解決思路:監(jiān)聽(tīng)mutation變化 更新頁(yè)面內(nèi)newAa
this.unsubscribe = this.$store.subscribe((mutation, state) => {
this.newAa = state.common.obj.a.aa;
});
},
destroyed(){
this.unsubscribe();
this.unsubscribe = null;
}