Accessing mutations or actions from one module to the next
-
Hello everyone,
I have been scratching my head on this and cannot work it out.
Let’s say you have multiple modules like here:
I would like to know if it would be correct to access an action from another action.
ie: I am in the action.js of the login module and would like(upon good login) to start the :this.$store.dispatch('alerts/alertGreen', 'You are logged in!');
which resides in my “alerts” module.
Would this be fine or makes sense?
All I am trying to do is regroup all my alerts into 1 module, all my common actions into another and then have separate modules for Login, Register and so on.
When currently run the dispatch from within the login module to get the alerts I receive this error:
Uncaught (in promise) TypeError: Cannot read property 'dispatch' of undefined
This is what I have in my actions.js in the alerts folder module:
import { Notify } from 'quasar'; export function alertGreen (context, message) { Notify.setDefaults({ position: 'top', timeout: 2500, textColor: 'white', actions: [{ icon: 'close', color: 'green' }], message: message }); } export function alertRed (context, message) { Notify.setDefaults({ position: 'top', timeout: 2500, textColor: 'white', actions: [{ icon: 'close', color: 'red' }], message: message }); }
Thank you.
-
I think your confusion is coming from misusing Vuex. The results of actions should be changes within the application’s state. I believe something to avoid is trying to use actions to call simple calls to functions. For that, you can just use vanilla JavaScript.
In other words, your alerts should be created and called like any other functions.
If you are trying to “globalize” your alerts in your application, try building a
boot
file and binding your action methods to the Vue instance. With this, you can call something likethis.alerts.alertRed (message)
in your components or if you want it outside of components, you can export the functions out of the boot file and import them in wherever you need them and doAlerts.alertRed(message)
.https://quasar.dev/quasar-cli/cli-documentation/boot-files#Introduction
I hope that makes sense. I’m no expert at Vuex either, so my advice should be taken with a grain of salt.
Scott
-
You can’t call
this.$store
inside your login module. What you could do is call an action there passing the dispatch function as a parameter and inside it callingdispatch('alerts/....', ...)
. -
This post is deleted!