You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

学习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:
    getters: {
      // 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;
      }
    }
    
    In a component, you access these with this.$store.getters.completedTodos or use the mapGetters helper 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:
    actions: {
      // 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);
      }
    }
    
    In a component, you trigger actions with this.$store.dispatch("fetchTodos") or use the mapActions helper to map them to local methods.

A Real-World Workflow Example

Let's tie all four concepts together with a common scenario:

  1. A component dispatches the fetchTodos action to load data from an API.
  2. The action finishes the async request, then commits the SET_TODOS mutation.
  3. The mutation updates the todos state in the store.
  4. Components can either access the raw todos state directly, or use the completedTodos getter to get a filtered list.
  5. When a user clicks to toggle a todo, the component dispatches the toggleTodo action, which updates the server first, then commits the TOGGLE_TODO mutation 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:17:59