问题
在vue组件内 通过commit 更新 vuex modules state 数据(obj),vue组件通过computed mapState获取不到最新的数据
//vuex
//项目初始化会设置state中obj为:
/* {
a: {
aa: '000',
bb: '222'
}
}*/
state: {
obj:{}
}
mutations: {
setObj(state, obj = {}) {
state.obj = Object.assign(state.obj, obj);
}
}
//vue
<template>
<div>
//页面初始化展示000,调用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() {
//这个aa就是computed里的
//这里也可以直接改写成 this.newAa = this.$store.state.common.obj.a.aa;
//主要是涉及对源代码修改的大小程度
this.newAa = this.aa;
//解决思路:监听mutation变化 更新页面内newAa
this.unsubscribe = this.$store.subscribe((mutation, state) => {
this.newAa = state.common.obj.a.aa;
});
},
destroyed(){
this.unsubscribe();
this.unsubscribe = null;
}