学习Vuex时无法区分四种状态,该如何解决?
Understanding Vuex's Core Concepts: State, Mutations, Getters & Actions
Hey there! Let's break down Vuex's core pieces clearly, with a focus on demystifying getters and actions since you already understand the basics of state and mutations.
Quick Recap: State & Mutations
First, let's refresh what you already know to set the stage:
- State: The single source of truth for your app's raw data. Think of it as a global data bucket that all components can pull from.
Example:state: { todos: [ { id: 1, text: "Master Vuex", done: false }, { id: 2, text: "Build a cool app", done: true } ] } - Mutations: The only way to directly modify state. They're synchronous functions that take the state and a payload, then update the state. No async allowed here—Vuex needs this to track state changes reliably for devtools.
Example:mutations: { TOGGLE_TODO(state, todoId) { const todo = state.todos.find(t => t.id === todoId); todo.done = !todo.done; } }
Getters: Computed Properties for Your Store
Think of getters as global computed properties for your Vuex store. Here's what you need to know:
- What they do: They take raw state (and even other getters) as inputs, process that data, and return a derived value. Just like component-level computed properties, they cache results—so they only re-run when the underlying state they depend on changes.
- Why use them?
- Avoid repeating the same filtering/sorting logic across multiple components. If three components need a list of completed todos, you write the logic once in a getter instead of three times.
- Keep your components clean—they can just use the pre-processed data from getters instead of manipulating state directly.
- Example:
Let's add getters to our todo store to get completed todos and their count:
In a component, you access these withgetters: { // Filter completed todos from state completedTodos: (state) => { return state.todos.filter(todo => todo.done); }, // Use another getter to calculate a count completedTodoCount: (state, getters) => { return getters.completedTodos.length; } }this.$store.getters.completedTodosor use themapGettershelper to map them to local computed properties.
Actions: Asynchronous Logic + Mutation Committers
Actions are where you handle all the async work in Vuex. Here's the breakdown:
- What they do: Actions are functions that handle asynchronous operations (like fetching data from an API, waiting for a timeout, or calling a third-party service). Once the async task finishes, they commit a mutation to update the state—they never modify state directly.
- Why use them?
- Mutations must be synchronous (as we mentioned earlier), so any async logic has to live in actions. This keeps Vuex's state change tracking predictable.
- Actions can chain other actions, or handle complex workflows (like fetching data, then updating multiple parts of state via multiple mutations).
- Example:
Let's add an action to fetch todos from an API, then update the state:
In a component, you trigger actions withactions: { // The context object gives us access to commit, dispatch, getters, etc. async fetchTodos({ commit }) { try { const response = await fetch("https://api.example.com/todos"); const todos = await response.json(); // Commit a mutation to update state once we have the data commit("SET_TODOS", todos); } catch (err) { console.error("Failed to fetch todos:", err); } }, // Actions can also accept a payload async toggleTodo({ commit }, todoId) { // First, update the todo on the server await fetch(`https://api.example.com/todos/${todoId}`, { method: "PATCH", body: JSON.stringify({ done: true }) }); // Then update local state via mutation commit("TOGGLE_TODO", todoId); } }this.$store.dispatch("fetchTodos")or use themapActionshelper to map them to local methods.
A Real-World Workflow Example
Let's tie all four concepts together with a common scenario:
- A component dispatches the
fetchTodosaction to load data from an API. - The action finishes the async request, then commits the
SET_TODOSmutation. - The mutation updates the
todosstate in the store. - Components can either access the raw
todosstate directly, or use thecompletedTodosgetter to get a filtered list. - When a user clicks to toggle a todo, the component dispatches the
toggleTodoaction, which updates the server first, then commits theTOGGLE_TODOmutation to update local state.
Key Cheat Sheet to Avoid Confusion
- State: Raw, unprocessed data (the "what" your app needs).
- Mutations: Synchronous state updaters (the "how to change state directly").
- Getters: Derived/processed state (the "what you need after filtering/sorting").
- Actions: Async handlers + mutation committers (the "how to handle async work before changing state").
内容的提问来源于stack exchange,提问作者spirytus
相关产品推荐
相关产品推荐

