Pinia(新一代狀態管理)

概述

Pinia 是 Vue 官方推薦的狀態管理工具,自 Vue 3 起逐漸取代 Vuex 成為主流。它具備以下特性:

  • 支援 Composition API,與 Vue 3 完美整合
  • 更簡潔直觀的語法
  • TypeScript 支援良好
  • 提供開發工具支援(如 Vue Devtools)

簡單來說,Pinia 是用來「管理全域資料」的工具,可以讓多個元件共享狀態,例如登入資訊、購物車內容等。


安裝

npm install pinia

註冊 Pinia 至 Vue 應用程式

// main.js
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'

const app = createApp(App)
const pinia = createPinia()

app.use(pinia)  // ✅ 註冊 Pinia
app.mount('#app')

建立一個 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++
    },
  },
})
  • defineStore 第1個參數為 store 的唯一 ID。
  • state 是一個函式,回傳初始狀態。
  • getters 是基於 state 的計算屬性。
  • actions 是用來修改狀態的函式,也可以執行非同步操作。

在元件中使用 Store

<script setup>
import { useCounterStore } from '@/stores/counter'

const counter = useCounterStore()

function add() {
  counter.increment()
}
</script>

<template>
  <div>
    <p>Count: {{ counter.count }}</p>
    <p>Double: {{ counter.doubleCount }}</p>
    <button @click="add">+1</button>
  </div>
</template>

目錄結構建議

src/
├── stores/
│   └── counter.js
├── main.js

你可以將所有 store 檔案集中放在 stores/ 目錄中,依功能拆分不同 store,例如 user.jscart.js 等。


額外補充

  • 若專案使用 TypeScript,建議將檔案副檔名改為 .ts,Pinia 對類型推斷支援非常良好。
  • 支援 Devtools(Vue Devtools)中觀察與除錯 store 的變化。
  • 可以使用 storeToRefs() 解構 store 的 state(但 getters 與 actions 不建議使用解構)。