Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change another module state from one module in Vuex

I have two modules in my vuex store.

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

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

In the module posts, before and after fetching posts, I want to change the property saving. I am doing it by calling commit('TOGGLE_SAVING') from one of the actions in the posts module.

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

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

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

How can I mutate state in another module using commit?

like image 843
Fizer Khan Avatar asked Mar 05 '17 08:03

Fizer Khan


People also ask

How do I change my Vuex state?

Vuex stores are reactive. When Vue components retrieve state from it, they will reactively and efficiently update if the store's state changes. You cannot directly mutate the store's state. The only way to change a store's state is by explicitly committing mutations.

What is Namespacing in Vuex?

In the previous Vuex tutorial, we learned that by default, getters, actions, and mutations inside modules are registered under the global namespace, which allows multiple modules to react to the same mutation or action.

Can you have multiple Vuex stores?

Vuex gives you the flexibility to manage multiple store modules based on how you'd like to structure your project.

What is the use of mapState in Vuex?

Mapping State Vuex provides a helper function called mapState to solve this problem. It is used for mapping state properties in the store to computed properties in our components. The mapState helper function returns an object which contains the state in the store.


2 Answers

Try it with following parameters as suggested here;

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

If you have namespaced set to true (in Nuxt that's the default when in modules mode), this becomes:

commit('loading/TOGGLE_LOADING', null, { root: true }) 
like image 52
Saurabh Avatar answered Sep 19 '22 17:09

Saurabh


you can use action to commit mutation which defined in another module,then you will modify state in another module.

like this:

posts: {   actions: {     toggleSavingActions(context) {       // some actions        context.commit("TOGGLE_SAVING"); // defined in loading module     }   } } 
like image 31
Julien Avatar answered Sep 21 '22 17:09

Julien