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
?
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.
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.
Vuex gives you the flexibility to manage multiple store modules based on how you'd like to structure your project.
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.
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 })
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 } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With