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

Pass multiple arguments when calling a Vuex action

April 12, 2022  ‐ 1 min read

At some point you will want to pass more than one argument to a Vuex action. However, adding more arguments to your action is not the way to go in Vuex. Instead you should wrap all the data you wish to pass in a single payload. Thus, what you probably want to use is a JavaScript object.

See the example below, where a username and password are to be passed to the authenticate Vuex action. Both username and password should be wrapped in a JavaScript object, this object can be passed as one argument to the Vuex action.

import { mapActions } from "vuex";

export default {
  data() {
    return {
      username: "",
      password: "",
    };
  },
  methods: {
    ...mapActions(["authenticate"]),
    logIn() {
      const payload = {
        username: this.username,
        password: this.password,
      };
      this.authenticate(payload);
    },
  },
};

In your Vuex action you can access the username and password as how you would access any property of a regular JavaScript object.

const store = new Vuex.Store({
  actions: {
    authenticate(context, payload) {
      api.post({
        username: payload.username,
        password: payload.password,
      });
    },
  },
});

If you prefer to do so you can use JavaScript Object Destructuring to clean up the action a bit.

const store = new Vuex.Store({
  actions: {
    authenticate(context, { username, password }) {
      api.post({ username, password });
    },
  },
});