How to define mutations in Vuex
Vuex mutations are the only way to change store state in Vue applications, providing predictable state updates with proper debugging and time-travel capabilities. As the creator of CoreUI with over 25 years of development experience, I use mutations extensively for reliable state management across enterprise applications. The most effective approach is defining mutations as synchronous functions that receive state and payload parameters for direct state modification. This ensures traceable, debuggable state changes that work seamlessly with Vue DevTools and maintain application predictability.
Define Vuex mutations as synchronous functions that directly modify state using descriptive names and payload parameters.
// store/index.js
import { createStore } from 'vuex'
const store = createStore({
state: {
user: null,
users: [],
loading: false,
errors: {}
},
mutations: {
// Simple state update
SET_LOADING(state, isLoading) {
state.loading = isLoading
},
// Object payload mutation
SET_USER(state, user) {
state.user = user
},
// Array operations
ADD_USER(state, user) {
state.users.push(user)
},
REMOVE_USER(state, userId) {
state.users = state.users.filter(user => user.id !== userId)
},
// Nested object updates
SET_USER_PROPERTY(state, { userId, property, value }) {
const user = state.users.find(u => u.id === userId)
if (user) {
user[property] = value
}
},
// Error handling
SET_ERROR(state, { field, message }) {
state.errors = { ...state.errors, [field]: message }
},
CLEAR_ERRORS(state) {
state.errors = {}
}
}
})
// Component usage
export default {
methods: {
updateUser() {
this.$store.commit('SET_USER', { id: 1, name: 'John' })
},
clearErrors() {
this.$store.commit('CLEAR_ERRORS')
}
}
}
This example shows different mutation patterns: simple value updates, object and array operations, nested property updates, and error handling. Mutations use uppercase naming convention and receive state as the first parameter and optional payload as the second. Each mutation performs a single, focused state change for maintainability.
Best Practice Note:
This mutation pattern is used in CoreUI’s Vuex modules for predictable state management. Always use mutations for state changes, never modify state directly in components, and keep mutations synchronous to maintain debugging capabilities.



