Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to dispatch actions between two namespaced vuex modules?

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?

like image 631
Chris Schmitz Avatar asked Mar 23 '17 18:03

Chris Schmitz


People also ask

How do you call one action from another action in Vuex?

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) { // }, }, });

Are Vuex actions synchronous?

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.

What is difference between dispatch and commit in Vuex?

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.

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.


2 Answers

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.

like image 97
Jake Avatar answered Sep 20 '22 17:09

Jake


dispatch('mobuleB/actionB', null, { root: true })

like image 36
Kaddu Livingstone Avatar answered Sep 22 '22 17:09

Kaddu Livingstone