一个vuex state中的数据存取问题

vuex的结构是这样的

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(){
            
        }
    }
})

父组件创建时

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

子组件实例化时

mounted () {
    //   获取项目信息
      this.projects = this.$store.getters.getAllProjs;
      this.projectNamesById = this.$store.getters.getProjectNamesById;
  },

然后现在有个问题,getAllProjs执行时机是在pushProjectsToStore之前,所以拿不到数据,请问如何解决

阅读 5.3k
3 个回答

建议子组件中直接用计算属性有修改的话就直接更新了,不然还要去监听vuex变更,更麻烦

computed: {
  projects() {
    return this.$store.getters.getAllProjs
  },
  projectNamesById() {
    return this.$store.getters.getProjectNamesById;
  }
},

用watch监听父组件的变化,不要放在mounted里。

computed: {

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

},
watch:{

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

}

}

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题