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.
Similar Reads
How to Pass Parameters in Computed Properties in VueJS ? In this article, we are going to learn how can we pass parameters in computed properties. The difference between a computed property and a method is that computed properties are cached, Methods are functions that can be called normal JS functions, but computed properties will be âre-calculatedâ anyt
2 min read
How to Pass Parameters to on:click in Svelte? Parameters are the data that you want to pass to a function when an event, such as a click, occurs. In Svelte, you can pass parameters to the on:click event handler in a couple of ways, either directly within the event handler or by using element references.In this article, we will explore two diffe
3 min read
How to pass two parameters to EventEmitter in Angular 9 ? In Angular, we can transmit the data in both directions i.e. inside: to the child component and outside: to the parent component. For sending data to the child component, we use property binding and for the latter we use EventEmitter. In this article, we will talk about the EventEmitter directive an
3 min read
How to pass parameters in Postman requests? Postman is an API(application programming interface) development tool that helps to build, test and modify APIs. It can make various types of HTTP requests(GET, POST, PUT, PATCH), save environments for later use, and convert the API to code for various languages(like JavaScript, and Python). In this
2 min read
How to Pass Parameter from TestNG.xml File? Parameters in TestNG allow you to configure test methods flexibly and make them more maintainable and reusable. The parameters feature allows you to pass data directly from the testng.xml file to test methods. This increases reusability at the suite level without the need to hard code values into th
3 min read
How to Add Multiple Data Types for Props in VueJS ? Props are used to pass the data from the parent component to the child component. We can pass the multiple data types for props by using the type option or by using the Dynamic props. In this article, we will see the practical implementation of adding multiple data types for props in VueJS. Table of
3 min read
How to Integrate Vite with Vue.js? Vite provides the flexibility and speed needed for modern web development by offering a fast-build tool and development server. Integrating Vite with Vue.js allows developers to use Viteâs efficient hot module replacement and optimized build processes while working with Vue's reactive framework. Thi
3 min read
Action vs Mutations in Vuex The Vuex is a state management library designed specifically for the Vue.js applications. It helps manage shared state in a centralized store, making it easier to handle complex applications. In Vuex, actions and mutations are crucial concepts for managing state changes. we will going to discuss bot
3 min read
How to Get Query Parameters from a URL in VueJS ? Query parameters are part of a URL that assigns values to specified parameters. They start after the question mark and are separated by ampersands ("&") in the URL. For example, in the URL https://example.com?name=John&age=23, name=John and age=23 are query parameters. The below-listed metho
8 min read
How to Loop X Times with v-for in VueJS? Vue.js is a progressive JavaScript framework widely used for building user interfaces. One of its core features is the v-for directive, which allows you to iterate over data or render a block of elements a specified number of times. we will explore various ways to loop X times using v-for in Vue.js.
3 min read