美文网首页
vuex state 数据更新 vue组件mapState获取不

vuex state 数据更新 vue组件mapState获取不

作者: 从不放弃 | 来源:发表于2022-10-10 17:06 被阅读0次

    问题

    在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;
    }
    

    参考

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

    相关文章

      网友评论

          本文标题:vuex state 数据更新 vue组件mapState获取不

          本文链接:https://www.haomeiwen.com/subject/axbgartx.html