Categories
Vue Answers

How to pass multiple parameters to mutation with Vuex?

Spread the love

Sometimes, we want to pass multiple parameters to mutation with Vuex.

In this article, we’ll look at how to pass multiple parameters to mutation with Vuex.

How to pass multiple parameters to mutation with Vuex?

To pass multiple parameters to mutation with Vuex, we can put all the values in the same object and destructure them in the mutation method.

For instance, we write

const store = new Vuex.Store({
  //...
  mutations: {
    authenticate(state, { token, expiration }) {
      localStorage.setItem("token", token);
      localStorage.setItem("expiration", expiration);
    },
  },
  //...
});

to add the authenticate mutation that takes an object with the token and expiration properties.

And then we can commit the mutation with

store.commit("authenticate", {
  token,
  expiration,
});

We call commit with the mutation name and the object with all the values we want to pass into the mutation’s 2nd parameter.

Conclusion

To pass multiple parameters to mutation with Vuex, we can put all the values in the same object and destructure them in the mutation method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

One reply on “How to pass multiple parameters to mutation with Vuex?”

Leave a Reply

Your email address will not be published. Required fields are marked *