鍍金池/ 問(wèn)答/HTML/ 一個(gè)vuex state中的數(shù)據(jù)存取問(wèn)題

一個(gè)vuex state中的數(shù)據(jù)存取問(wèn)題

vuex的結(jié)構(gòu)是這樣的

export default new Vuex.Store({
    state:{
        projects:[],
    },
    getters:{
        getAllProjs(state){
            return state.projects;
        },
        getProjectNamesById(state){
            return state.projects.map( proj => proj.name )
        }
    },
    mutations:{
        pushProjectsToStore(state,data){
            state.projects = data;
        },
    },
    actions:{
        pushProjectsToStore(){
            
        }
    }
})

父組件創(chuàng)建時(shí)

beforeCreate(){
      this.$queryProject().then( res => this.$store.commit('pushProjectsToStore',res.data) )
  },

子組件實(shí)例化時(shí)

mounted () {
    //   獲取項(xiàng)目信息
      this.projects = this.$store.getters.getAllProjs;
      this.projectNamesById = this.$store.getters.getProjectNamesById;
  },

然后現(xiàn)在有個(gè)問(wèn)題,getAllProjs執(zhí)行時(shí)機(jī)是在pushProjectsToStore之前,所以拿不到數(shù)據(jù),請(qǐng)問(wèn)如何解決

回答
編輯回答
失心人

computed: {

...mapGetters(["getAllProjs","getProjectNamesById"])

},
watch:{

getAllProjs(newVal,oldVal){
    console.log('vuex 中上一次的值',oldVal);
    console.log('vuex 中更新后的值',newVal);
},
getProjectNamesById(newVal,oldVal){

}

}

2017年7月23日 12:18
編輯回答
赱丅呿

建議子組件中直接用計(jì)算屬性有修改的話就直接更新了,不然還要去監(jiān)聽vuex變更,更麻煩

computed: {
  projects() {
    return this.$store.getters.getAllProjs
  },
  projectNamesById() {
    return this.$store.getters.getProjectNamesById;
  }
},
2017年2月6日 15:07
編輯回答
誮惜顏

用watch監(jiān)聽父組件的變化,不要放在mounted里。

2017年3月16日 16:26