What is Mutation in Vuex: Simple Explanation and Example
mutation is a special function that changes the state in a Vuex store. Mutations are the only way to update state directly, ensuring changes are tracked and predictable.How It Works
Think of Vuex state as a shared notebook where your app's data lives. A mutation is like a pen that lets you write or erase on that notebook. But to keep things neat and organized, Vuex only allows changes through these mutations, so you always know when and how the data changes.
When you want to update the state, you call a mutation with the new information. Vuex then runs that mutation function, which changes the state. This process helps keep your app's data flow clear and easy to follow, like having a single path for all updates.
Example
This example shows a Vuex store with a mutation that adds a new item to a list in the state.
import { createStore } from 'vuex'; const store = createStore({ state() { return { items: [] }; }, mutations: { addItem(state, newItem) { state.items.push(newItem); } } }); // Usage example: store.commit('addItem', 'apple'); console.log(store.state.items);
When to Use
Use mutations whenever you need to change the Vuex state. This includes adding, removing, or updating data that your app shares across components. For example, when a user adds a product to a shopping cart, a mutation updates the cart state.
Mutations keep your app's data changes clear and predictable, which helps avoid bugs and makes debugging easier. Always use mutations instead of changing state directly to follow Vuex rules.
Key Points
- Mutations are synchronous functions that update Vuex state.
- They receive the current state and a payload with new data.
- State changes only happen inside mutations to keep tracking simple.
- You call mutations using
store.commit. - Mutations help maintain a clear and predictable data flow.