vuex state 數(shù)據(jù)更新 vue組件mapState獲取不到

問(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;
}

參考

https://vuex.vuejs.org/zh/api/#subscribe

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容