Understanding Vuex Core Features
🎯 Introduction
As you learn the Vue ecosystem, you will likely encounter Vuex for state management. Its core features—getters, actions, and mutations—help you manage complex application state with a clear, maintainable, and efficient code structure. This article introduces these concepts from the ground up and shows how to use them in practice.
✨ Getters: Computed Values from State
Let's start with getters. You may already know Vue's computed properties: they derive new values from existing data and cache their results, recalculating only when their dependencies change.
Vuex getters work similarly. They compute derived state from the store's state, centralizing complex logic instead of repeating it across components.
For example, if your state contains a list of shopping cart items, a getter is a good place to calculate the cart's total price.
const store = new Vuex.Store({
state: {
cart: [
{ id: 1, name: 'Phone', price: 2999, quantity: 2 },
{ id: 2, name: 'Headphones', price: 199, quantity: 1 },
],
},
getters: {
totalPrice(state) {
return state.cart.reduce((sum, item) => sum + item.price * item.quantity, 0);
},
},
});
You can then read the total in a component through this.$store.getters.totalPrice.
🚀 Actions: Handling Asynchronous Operations
Mutations update Vuex state synchronously, but applications often need asynchronous operations such as requests to backend APIs. Vuex provides actions to keep this asynchronous logic separate from state changes.
Actions handle operations such as network requests and timers. Trigger them with dispatch. They should update state by committing mutations rather than modifying it directly.
For example, suppose you need to fetch user data from an API:
const store = new Vuex.Store({
state: {
userInfo: null,
},
mutations: {
setUserInfo(state, userData) {
state.userInfo = userData;
},
},
actions: {
fetchUserInfo(context) {
// Simulate an asynchronous request
setTimeout(() => {
const data = { name: 'Zhang San', age: 25 };
context.commit('setUserInfo', data);
}, 1000);
},
},
});
Dispatch the action from a component:
this.$store.dispatch('fetchUserInfo');
This gives asynchronous operations and state changes clearly separated responsibilities.
🔍 Why Separate Mutations and Actions?
There are two main reasons to distinguish mutations from actions:
1. Mutations keep state changes synchronous and traceable
Vuex requires all state changes to go through mutations, and mutations must be synchronous. This makes the sequence of changes predictable and supports debugging and history tracking.
For example, during development you can inspect each mutation in Vue Devtools to see how state changes step by step.
2. Actions handle asynchronous operations and business logic
Putting asynchronous code directly in mutations makes state changes unpredictable and difficult to track. Actions act as an intermediate layer: they handle asynchronous requests and complex business logic, then commit mutations to update state synchronously. This separation keeps code clear and easier to maintain.
🎯 Practical Example: Managing Login State with Vuex
Let's simulate a user login flow in a short exercise.
- Store user information and login state in state
- Update login state and user information synchronously in mutations
- Simulate an asynchronous login request in an action
const store = new Vuex.Store({
state: {
user: null,
isLoggedIn: false,
},
mutations: {
loginSuccess(state, userData) {
state.user = userData;
state.isLoggedIn = true;
},
logout(state) {
state.user = null;
state.isLoggedIn = false;
},
},
actions: {
login(context, credentials) {
// Simulate an asynchronous API request
return new Promise(resolve => {
setTimeout(() => {
// Perform a simple validation check
if (credentials.username === 'admin' && credentials.password === '1234') {
const userData = { username: 'admin', name: 'Administrator' };
context.commit('loginSuccess', userData);
resolve(true);
} else {
resolve(false);
}
}, 1000);
});
},
logout(context) {
context.commit('logout');
},
},
getters: {
welcomeMessage(state) {
return state.isLoggedIn ? `Welcome back, ${state.user.name}!` : 'Please log in';
},
},
});
Example usage:
store.dispatch('login', { username: 'admin', password: '1234' }).then(success => {
if (success) {
console.log(store.getters.welcomeMessage);
} else {
console.log('Login failed');
}
});
❓ Knowledge Check
Q1: Why must mutations be synchronous?
Synchronous mutations give state changes a clear order, making them easier to debug and trace back. Asynchronous changes introduce uncertainty about state and make state management less reliable.
Q2: Can you change state directly in an action?
No. Actions should change state only by committing mutations, keeping the update process consistent.
Q3: How do getters differ from state?
State holds the underlying data. Getters compute derived values from that data, much like computed properties.
🧪 Practice
Exercise 1
Implement a Vuex store that manages a todo list, with features to add todos and mark them as complete. Use mutations to update state synchronously and an action to simulate asynchronously loading the initial todos from a server.
Exercise 2
Write a getter that counts completed todos and display the count in a component.
🎉 You now understand getters, actions, and mutations in Vuex!
Getting Started with Vuex
Learn to install, configure, and use Vuex in a Vue 2 project, understand state and mutations, and avoid common pitfalls.
Modules and Advanced Usage
Learn to organize Vuex into modules, simplify component code, and persist state for more efficient state management in large applications.
