How to Pass Multiple Parameters to Mutation in Vuex?
Last Updated :
17 Sep, 2024
We will explore how to pass multiple parameters to a mutation in Vuex, which is a state management library for VueJS applications. Vuex allows you to manage the state of your application efficiently, and understanding how to work with mutations is crucial when building scalable Vue applications.
Vuex mutations modify the state of the store in a Vue application. By default, mutations only take one argument, the payload. However, there are situations where you might want to pass multiple parameters. In Vuex, you can either pass an object containing multiple values or use destructuring inside the mutation to handle multiple parameters.
Steps to set up the application
Step 1: Install Vue CLI
If you haven’t installed the Vue CLI, install it globally on your machine by running:
npm install -g @vue/cli
Step 2: Create a New Vue Project
In your terminal or command prompt, run the following command to create a new Vue 3 project:
vue create vuex-app
Step 3: Navigate to Your Project Directory
cd vuex-app
Step 4: Install Vuex
If Vuex is not installed automatically, install it using the following command:
npm install vuex --save
Step 5: Create the Vuex Store
Create a folder named store inside the src directory and add a file named index.js:
mkdir src/store
echo > src/store/index.js
This file will contain the Vuex store where you will define the state, mutations, actions, and getters.
Project Structure:
Project structureUpdated dependencies:
"dependencies": {
"core-js": "^3.8.3",
"vue": "^3.2.13",
"vuex": "^4.0.2"
},
"devDependencies": {
"@babel/core": "^7.12.16",
"@babel/eslint-parser": "^7.12.16",
"@vue/cli-plugin-babel": "~5.0.0",
"@vue/cli-plugin-eslint": "~5.0.0",
"@vue/cli-service": "~5.0.0",
"eslint": "^7.32.0",
"eslint-plugin-vue": "^8.0.3"
},
Step 6: Initialize Vuex Store
In store/index.js, set up your Vuex store as follows:
import { createStore } from 'vuex';
export default createStore({
state: {
user: {
name: '',
age: null,
city: ''
}
},
mutations: {
updateUser(state, payload) {
state.user.name = payload.name;
state.user.age = payload.age;
state.user.city = payload.city;
}
},
actions: {
updateUser({ commit }, payload) {
commit('updateUser', payload);
}
},
getters: {
getUser(state) {
return state.user;
}
}
});
Step 7: Configure Vuex in the Main Application
In src/main.js, import and configure Vuex to work with the Vue application:
import { createApp } from 'vue';
import App from './App.vue';
import store from './store';
const app = createApp(App);
app.use(store);
app.mount('#app');Passing an Object as the Payload
This is the most common and flexible approach. Instead of passing individual parameters, you pass a single object containing all the data you want to mutate in the state. The object is then accessed in the mutation, and the properties of this object are used to update the state.
You can pass an entire object as the payload when committing a mutation. This object will contain all the parameters as key-value pairs. The mutation then extracts the values from the object to update the state.
- Pros: Simple and organized way to handle multiple values.
- Use case: Ideal when dealing with related data that can logically be grouped into an object
Syntax:
this.$store.commit('mutationName', { param1, param2, param3 });Example: This example shows the use of above explained approach.
JavaScript
// store/index.js
import { createStore } from 'vuex';
export default createStore({
state: {
user: {
name: '',
age: null,
city: ''
}
},
mutations: {
updateUser(state, payload) {
state.user.name = payload.name;
state.user.age = payload.age;
state.user.city = payload.city;
}
},
actions: {
updateUser({ commit }, payload) {
commit('updateUser', payload);
}
},
getters: {
getUser(state) {
return state.user;
}
}
});
JavaScript
// src/App.vue
<template>
<div>
<input v-model="userName" placeholder="Enter name" />
<input v-model="userAge" type="number" placeholder="Enter age" />
<input v-model="userCity" placeholder="Enter city" />
<button @click="updateUserInfo">Update User Info</button>
</div>
</template>
<script>
export default {
data() {
return {
userName: '',
userAge: null,
userCity: ''
};
},
methods: {
updateUserInfo() {
this.$store.commit('updateUser', {
name: this.userName,
age: this.userAge,
city: this.userCity
});
}
}
};
</script>
Using Individual Parameters with Destructuring
Another method is to pass an object as the payload, but instead of accessing individual values via dot notation, destructure the object inside the mutation. This makes the code cleaner, and individual properties can be handled directly.
- Pros: Cleaner syntax and more explicit handling of parameters.
- Use case: Useful when you want direct access to the individual parameters within the mutation.
Syntax:
mutations: {
mutationName(state, { param1, param2, param3 }) {
// update state
}
}Example: This example shows the use of above explained approach.
JavaScript
// store/index.js
import { createStore } from 'vuex';
export default createStore({
state: {
user: {
name: '',
age: null,
city: ''
}
},
mutations: {
updateUser(state, payload) {
state.user.name = payload.name;
state.user.age = payload.age;
state.user.city = payload.city;
}
},
actions: {
updateUser({ commit }, payload) {
commit('updateUser', payload);
}
},
getters: {
getUser(state) {
return state.user;
}
}
});
JavaScript
// main.js
import { createApp } from 'vue';
import App from './App.vue';
import store from './store';
const app = createApp(App);
app.use(store); // Vue 3 uses `app.use` instead of `Vue.use`
app.mount('#app');
JavaScript
// src/App.vue
<template>
<div>
<h2>Update User Information</h2>
<form @submit.prevent="updateUserInfo">
<div>
<label for="name">Name:</label>
<input id="name" v-model="userName" placeholder="Enter name" required />
</div>
<div>
<label for="age">Age:</label>
<input id="age" v-model.number="userAge" type="number" placeholder="Enter age" required />
</div>
<div>
<label for="city">City:</label>
<input id="city" v-model="userCity" placeholder="Enter city" required />
</div>
<button type="submit">Update User Info</button>
</form>
<h3>Updated User Info:</h3>
<p><strong>Name:</strong> {{ user.name }}</p>
<p><strong>Age:</strong> {{ user.age }}</p>
<p><strong>City:</strong> {{ user.city }}</p>
</div>
</template>
<script>
import { mapGetters, mapActions } from 'vuex';
export default {
name: 'UserForm',
data() {
return {
userName: '',
userAge: null,
userCity: ''
};
},
computed: {
...mapGetters(['getUser']),
user() {
return this.getUser;
}
},
methods: {
...mapActions(['updateUser']),
updateUserInfo() {
// Optionally, add validation or processing here
this.updateUser({
name: this.userName,
age: this.userAge,
city: this.userCity
});
// Clear the form fields after submission
this.userName = '';
this.userAge = null;
this.userCity = '';
}
}
};
</script>
<style scoped>
form {
display: flex;
flex-direction: column;
max-width: 300px;
}
div {
margin-bottom: 10px;
}
label {
margin-bottom: 5px;
}
input {
padding: 5px;
font-size: 1em;
}
button {
padding: 10px;
font-size: 1em;
cursor: pointer;
}
h3 {
margin-top: 20px;
}
</style>
Step 8: Start the Development Server
In your project directory, run:
npm run serve
Step 9: Open the Application in Your Browser
- Navigate to http://localhost:8080/ in your web browser. You should see the Update User Information form.
- In my case 8080 port is already used so my applicatin is running on http://localhost:8081/.
Output: Once you fill out the form and click Update User Info, the user data will be updated in the Vuex store. You can view the changes using Vue DevTools to monitor the state:
Output:Conclusion
Passing multiple parameters to Vuex mutations is straightforward and flexible. You can choose between passing an object as the payload or using destructuring, depending on your needs. Understanding these approaches will help you manage complex state changes in your Vue applications, making them more maintainable and scalable.
By following this guide, you now have a complete understanding of how to handle multiple parameters in Vuex mutations, along with a working example you can implement in your own projects.
Explore
JavaScript Basics
Array & String
Function & Object
OOP
Asynchronous JavaScript
Exception Handling
DOM
Advanced Topics