Change a different module state from one module in Vuex

I have two modules in my vuex repository.

var store = new Vuex.Store({ modules: { loading: loading posts: posts } }); 

In the loading module, I have a saving property that can be set to either true or false , and also have a mutation function called TOGGLE_SAVING to set this property.

In the posts module, before and after retrieving posts, I want to change the saving property. I do this by calling commit('TOGGLE_SAVING') from one of the actions in the posts module.

 var getPosts = function (context) { contex.commit(TOGGLE_LOADING); }; 

When he tried to commit, I got the following error in the console

 [vuex] unknown local mutation type: TOGGLE_LOADING, global type: posts/TOGGLE_LOADING 

How can I change state in another module using commit ?

+5
source share
2 answers

Try with the following options suggested here ;

 commit('TOGGLE_SAVING', null, { root: true }) 

You may need to set namespaced to true.

+4
source

you can use action to fix the mutation defined in another module, then you will change state in another module.

like this:

 posts: { actions: { toggleSavingActions(context) { // some actions context.commit("TOGGLE_SAVING"); // defined in loading module } } } 
+1
source

Source: https://habr.com/ru/post/1265052/


All Articles