Location>code7788 >text

Vuex: The "steward" who makes state management no longer have a headache

Popularity:864 ℃/2025-03-01 12:04:24

If you are developing an application but find yourself struggling with state sharing issues between various components, then Vuex is the "super housekeeper" you need. Vuex is a state management library specially designed for. It is like a caring butler, helping you centrally manage the state of all components. Next, we will take you into a light and humorous way to take you into the four core concepts of Vuex: State, Getters, Mutations, and Actions.

1. State: The "locker" at home
Imagine that you have a huge storage locker in your home that holds everything you need, such as snacks, clothes, tools, and more. In Vuex, State is this "locker", which is the centralized storage place for the entire application state.

Sample code

// 
import Vue from 'vue';
import Vuex from 'vuex';

(Vuex);

const store = new ({
state: {
user: {
name: 'John Doe',
age: 30,
},
cart: [], // Shopping cart},
});



export default store;
In this example, there are two things in our "locker":

user: Store user's personal information.
cart: Stores the contents of the shopping cart.
Why do you need a State?

It's like a global variable, but safer and more controllable.
All components can take things from this "locker" (read the status) or put things inside (modify the status).
2. Getters: a smart "assistant"
Sometimes, you may need to do some processing on the things in the locker, such as counting how many items are in the shopping cart, or splicing out the user's complete information. At this time, Vuex provides a "assistant" called Getters.

Sample code

const store = new ({
state: {
cart: [],
user: {
name: 'John Doe',
age: 30,
},
},
getters: {
cartItemCount: (state) => {
return ; // Return to the quantity of items in the shopping cart},
fullName: (state) => {
return `${} (${} years old)`; // Return the complete user information},
},
});

In this example, we define two "assistants":

cartItemCount: Tell you how many items are in the shopping cart.
fullName: splice the user's name and age into a complete string.
The Benefits of Getters

They are like computed properties in Vue components that are automatically updated according to changes in State.
If you need to do some complex calculations or filtering of the state, Getters is the best choice.
3. Mutations: Strict "administrator"
Although you can put things directly into the locker, this can lead to confusion. Vuex proposes a rule: all state modifications must be done through Mutations. Mutations is like a strict administrator, ensuring that every step of the operation is recorded, which facilitates follow-up tracking and debugging.

Sample code

const store = new ({
state: {
cart: [],
},
mutations: {
addToCart(state, product) {
(product); //Add items to cart
},
removeFromCart(state, productIndex) {
(productIndex, 1); //Remove items from cart
},
},
});

 



In this example, we define two "administrator" commands:

addToCart: Responsible for adding items to the shopping cart.
removeFromCart: Responsible for removing items from the shopping cart.
Why Mutations are needed?

Ensure that changes in status are traceable.
All state changes must be done through Mutations, which can avoid confusion caused by arbitrary modification of states.
Things to note

Mutations must be synchronous! If you need to handle asynchronous operations, please leave it to Actions.
4. Actions: Flexible "courier"
Sometimes, you need to get something out from outside, like buying a new toy online and put it in the locker. At this time, Vuex provides a "courier" called Actions, which is specifically responsible for handling these asynchronous tasks.

Sample code

const store = new ({
state: {
cart: [],
},
mutations: {
addToCart(state, product) {
(product);
},
},
actions: {
fetchProductAndAddToCart({ commit }, productId) {
// Simulate to obtain product data from the APIsetTimeout(() => {
const product = { id: productId, name: 'Sample Product' };
commit('addToCart', product); // Call mutation to modify the status}, 1000);
},
},
});



In this example, we define a "courier" task:

fetchProductAndAddToCart: Simulates getting product data from the server, and then calls addToCart to add the product to the cart.
Features of Actions

It can contain asynchronous logic, such as getting data from a server.
After completion, you can call Mutations by commit to update the status.
Why do you need Actions?

Actions are your best choice when handling asynchronous operations.
It separates asynchronous logic from state modifications, making the code clearer.
5. Summary: Vuex's "Family Bucket"
Vuex provides a complete set of tools to help you manage the status of your application. Let's review the division of roles of these four "family members":

State: The "locker" at home stores all data that needs to be shared.
Getters: A clever "assistant" responsible for calculating and deriveing ​​new data.
Mutations: Strict "administrator" to ensure that status changes are orderly and traceable.
Actions: Flexible "courier" who handles asynchronous tasks and calls Mutations to update status.
By using these four tools reasonably, Vuex can make your application status management clearer, more efficient and controllable.

Additional Knowledge: Modular Vuex
As your application gets bigger, Vuex offers a powerful feature—modularity. You can split states, Getters, Mutations, and Actions into multiple modules, each focusing on managing specific features.

Sample code

const moduleA = {
state: { count: 0 },
mutations: { increment(state) { ++; } },
};

const moduleB = {
state: { text: '' },
actions: { updateText({ commit }, newText) { commit('setText', newText); } },
mutations: { setText(state, newText) {  = newText; } },
};

const store = new ({
modules: {
a: moduleA,
b: moduleB,
},
});

In this example, we divide the state into two modules: moduleA and moduleB, each module has its own independent state and operation logic.

Conclusion
Vuex is a very powerful tool that not only helps you centrally manage state, but also provides clear structure and rules to make your application state management more orderly. Whether it is a simple single-page application or a complex enterprise-level project, Vuex can protect you!

So, next time you are facing the problem of status management, you might as well try this "super butler"!