Vuex Mutation running, but component not updating until manual commit in vue dev tools

前端 未结 3 2025
天涯浪人
天涯浪人 2021-01-11 18:22

I have a vue component that I can\'t get to update from a computed property that is populated from a service call.

Feed.vue



        
相关标签:
3条回答
  • 2021-01-11 18:40

    In the same way that component data properties need to be initialised, so too does your store's state. Vue cannot react to changes if it does not know about the initial data.

    You appear to be missing something like...

    state: {
      status: { loading: true },
      currentFeed: {}
    }
    

    Another option is to use Vue.set. See https://vuex.vuejs.org/guide/mutations.html#mutations-follow-vue-s-reactivity-rules...

    Since a Vuex store's state is made reactive by Vue, when we mutate the state, Vue components observing the state will update automatically. This also means Vuex mutations are subject to the same reactivity caveats when working with plain Vue

    0 讨论(0)
  • 2021-01-11 18:51

    Sometimes updating property that are not directly in the state is the problem

    {
       directprop: "noProblem",
       indirectParent: {
          "test": 5 // this one has a problem but works if we clone the whole object  indirectParent
       }
    }
    

    but it is a temporary solution, it should help you to force update the state and discover what is the real problem.

    0 讨论(0)
  • 2021-01-11 18:55

    Hey for all the people coming to this and not being able to find a solution. The following was what worked for me:

    Declaring base state:

    state: {
      mainNavData: [],
    }
    

    Then I had my action which is calling the now fixed mutation:

    actions : {
      async fetchMainNavData({ commit }) {
        var response = await axios.get();
        commit('setMainNavData', response));
      },
      
    };
    

    Now my mutation is calling this updateState() function which is key to it all

    mutations = {
      setMainNavData(state, navData) {
        updateState(state, 'mainNavData', navData);
      },
    };
    

    This is what the updateState function is doing which solved my issues.

    const updateState = (state, key, value) => {
      const newState = state;
      newState[key] = value;
    };
    

    After adding updateState() my data reactively showed up in the frontend and I didn't have to manually commit the data in Vue tools anymore.

    please note my store is in a different file, so its a little bit different.

    Hope this helps others!

    0 讨论(0)
提交回复
热议问题