Actions
Actions are the store's methods: the place for logic that changes state, including async work.
In this page:
Syntax
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
<!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
- Putting business logic in components
- Forgetting to await async actions
- 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: