Is it possible to dispatch an action between namespaced modules?
E.g. I have vuex modules "gameboard" and "notification". Each are namespaced. I would like to dispatch an action from the gameboard to the notification module.
I thought I could use the module name in the dispatch action name like this:
// store/modules/gameboard.js const actions = { myaction ({dispatch}) { ... dispatch('notification/triggerSelfDismissingNotifcation', {...}) } } // store/modules/notification.js const actions = { triggerSelfDismissingNotification (context, payload) { ... } }
But when I try to do this I get errors that make me thing vuex is trying to dispatch an action within my gameboard module:
[vuex] unknown local action type: notification/triggerSelfDismissingNotification, global type: gameboard/notification/triggerSelfDismissingNotification
Is there a way of dispatching from vuex module to module or do I need to create some kind of a bridge in the root vuex instance?
You can call another Vuex action by passing the name of that action as a string as the first argument of dispatch : const store = new Vuex. Store({ actions: { walk(context) { context. dispatch("goForward"); }, goForward(context) { // }, }, });
Vuex actions and their async nature. Mutations are used to mutate the state and they are always synchronous, actions are used to perform certain operations, usually asynchronous, before mutation is commited.
Dispatch triggers an action whereas commit triggers a mutation. $dispatch is always used from your methods in routes/components. It sends a message to Vuex store to perform some action. The action can be performed any time after the current tick so that it will not affect the frontend performance.
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.
You just need to specify that you're dispatching from the root context:
// from the gameboard.js vuex module dispatch('notification/triggerSelfDismissingNotifcation', {...}, {root:true})
Now when the dispatch reaches the root it will have the correct namespace path to the notifications module (relative to the root instance).
This is assuming you're setting namespaced: true
on your vuex store module.
dispatch('mobuleB/actionB', null, { 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