Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vuex | How to commit a global mutation in a module action?

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?

like image 263
Julien Le Coupanec Avatar asked Jun 18 '17 18:06

Julien Le Coupanec


People also ask

How do you commit a mutation from another module Vuex?

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 .

Can I call action from mutation Vuex?

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.

What is difference between mutation and action in Vuex?

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.

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.


1 Answers

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 }) 
like image 75
Julien Le Coupanec Avatar answered Oct 05 '22 16:10

Julien Le Coupanec