I have an action in a namespaced module and a global mutation (i.e. not in a module). I would like to be able to commit the global mutation inside the action.
// Global mutation export default { globalMutation (state, payload) { ... } } // Action in a namespaced module export default { namespaced: true, actions: { namespacedAction ({ commit, dispatch, state }, payload) { commit({ type: 'globalMutation' }) } } }
When the namespaced action is dispatched, Vuex displays:
[vuex] unknown local mutation type: globalMutation, global type: module/globalMutation
Is there an option I can pass to the commit
function to call this global mutation?
To change another module state from one module in Vuex, we can call commit with the mutation name with the root option set to true . commit("TOGGLE_LOADING", null, { root: true }); to call commit to commit the TOGGLE_LOADING mutation with root set to true .
In Vuex, actions are functions that call mutations. Actions exist because mutations must be synchronous, whereas actions can be asynchronous. You can define actions by passing a POJO as the actions property to the Vuex store constructor as shown below. To "call" an action, you should use the Store#dispatch() function.
Mutations, as the name suggests is used to modify/mutate your state object. Actions are quite similar to mutations, but instead of mutating the state, Actions commit mutations. Actions can contain any arbitrary asynchronous code or business logic.
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.
Looks like I just found a way with the { root: true }
parameter.
commit('globalMutation', payload, { root: true })
If module is namespaced, use global path instead:
commit('module/mutation', payload, { root: true })
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