Join my Laravel for REST API's course on Udemy 👀

Call Vuex action from another action

April 9, 2022  ‐ 2 min read

Calling a vuex action from another action requires the use of a special function: dispatch.

The dispatch function is available from the context that is passed as a first argument to your Vuex actions. 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) {
      //
    },
  },
});

Or you can use JavaScript Object Destructuring to access dispatch directly.

const store = new Vuex.Store({
  actions: {
    walk({ dispatch }) {
      dispatch("goForward");
    },
    goForward(context) {
      //
    },
  },
});

Dispatch with arguments

Arguments to the Vuex action you wish to call can be passed as second argument to dispatch:

const store = new Vuex.Store({
  actions: {
    walk({ dispatch }) {
      const speed = "4km/h";
      dispatch("goForward", speed);
    },
    goForward(context, payload) {
      // The value of the payload is: '4km/h'
    },
  },
});

All that the arguments that you wish to pass to another action should be in the payload. Vuex doesn't allow you to add more arguments, instead you can wrap the other data in a JavaScript object.

Dispatch in other module

If you are working with Vuex modules, you may at some point want to call an action in another module. In that case you need to pass { root: true } as a 3rd argument to dispatch. Order matters here, so even if the Vuex action you wish to call doesn't require a payload you still need to pass something (an empty object or null will do).

const store = new Vuex.Store({
  actions: {
    walk({ dispatch }) {
      const speed = "4km/h";
      dispatch("movement/goForward", speed, { root: true });
    },
  },
});