87
Vue 3 學習之旅
狀態管理
Day 87: Pinia 的 State, Getters, Actions
·6 分鐘閱讀·狀態管理
摘要
Pinia 的核心由三個概念組成:State (狀態)、Getters (計算值) 和 Actions (方法)。
定義與說明
State:定義 Store 核心資料的地方,它必須是一個回傳初始狀態物件的函式。
Getters:相當於 Store 的計算屬性 (computed)。它們可以根據 state 派生出新的值,並且結果會被快取。
Actions:相當於 Store 的方法 (methods)。它們可以用於定義業務邏輯,並在內部修改 state。Actions 可以是同步的,也可以是異步的。
實作範例
完整的 Pinia Store 示例
// stores/counter.js
import { defineStore } from 'pinia';
export const useCounterStore = defineStore('counter', {
state: () => ({ count: 0 }),
getters: {
doubleCount: (state) => state.count * 2,
},
actions: {
increment() {
this.count++;
},
},
});
結論
State, Getters, Actions 的清晰劃分,讓 Pinia 的狀態管理流程非常直觀且易於維護,與 Vue 元件的 data, computed, methods 概念如出一轍。
State Getters Actions