← Back to Vue.js Course | Chapter 8: State Management | Lesson 5 of 6

Actions

Actions are the store's methods: the place for logic that changes state, including async work.

In this page:

  1. Actions
Syntax
markup
actions: {
  actionName(param) {
    this.property = param;
  },
  async fetchData() {
    this.property = await apiCall();
  }
}

Actions

Actions are plain functions with this bound to the store. They can be async, call other actions and access other stores. Components call them like methods. Keeping mutations inside actions centralizes business logic and makes it easy to test.

Note: Actions may be async and can return values or promises.

Example: Actions

markup
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
  <script src="https://unpkg.com/[email protected]/lib/index.iife.js"></script>
  <script src="https://unpkg.com/pinia@2/dist/pinia.iife.js"></script>
</head>
<body>
<div id="app"><p>{{ todos.items.join(", ") || "empty" }} ({{ todos.loading ? "loading" : "idle" }})</p></div>
<script>
  const useTodos = Pinia.defineStore("todos", {
    state: () => ({ items: [], loading: false }),
    actions: {
      async load() {
        this.loading = true;
        await new Promise((r) => setTimeout(r, 10));   // pretend fetch
        this.items = ["write docs", "ship code"];
        this.loading = false;
      },
      add(text) { this.items.push(text); },
    },
  });
  const app = Vue.createApp({ setup() { return { todos: useTodos() }; } });
  app.use(Pinia.createPinia());
  app.mount("#app");
  const s = useTodos();
  s.load().then(() => { s.add("relax"); Vue.nextTick(() => console.log(document.querySelector("p").textContent)); });
</script>
</body>
</html>

<!-- Output:
Rendered: write docs, ship code, relax (idle)
console: write docs, ship code, relax (idle)
-->
Live Example
Related Topics
Common Mistakes
  1. Putting business logic in components
  2. Forgetting to await async actions
  3. Using arrow functions that lose this
Chapter Summary
  • Actions are store methods
  • They can be async
  • this refers to the store
  • They centralize logic
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.