Pinia
Pinia 是 Vue 官方的狀態管理庫(名字來自西班牙文 piña,鳳梨)。當很多不相鄰的元件要讀寫同一份資料(目前使用者、購物車、主題),把狀態放到 store,就不必一層層 props 往下傳。
Vuex 是舊方案,新專案用 Pinia。官方:Introduction。
定義一個 store
// stores/counter.js
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
export const useCounterStore = defineStore('counter', () => {
const count = ref(0)
const doubled = computed(() => count.value * 2)
function increment() {
count.value++
}
return { count, doubled, increment }
})
這是 Setup Store 寫法,跟 <script setup> 同一套心智模型。元件裡:
<script setup>
import { useCounterStore } from '@/stores/counter'
const counter = useCounterStore()
</script>
<template>
<button @click="counter.increment">{{ counter.count }}</button>
</template>
在 main.js 記得 app.use(createPinia())。DevTools 可以看到每個 store 的狀態與時間旅行除錯。
什麼時候該用
- 該用:登入態、多頁都要的清單、跨 layout 的 UI 狀態。
- 不該用:只有父子兩層在用的資料,props/emits 就夠;把所有伺服器資料都塞進 Pinia 也不必,元件內
ref+ composable 往往更單純。
需要把非同步請求的快取、重新驗證做成基礎設施時,可以再看 Pinia 作者談的 Pinia Colada(進階,見 影音教學)。入門把「一份共享狀態、幾個 action」跑通即可。
推薦影音
Getting Started with Pinia
來源:Vue Mastery 約 10 分鐘
說明 Pinia 要解決什麼問題、store 怎麼切,並帶第一個 store。對應本頁「定義一個 store」。完整課在 Pinia Fundamentals。
Pinia Crash Course #1 — What is Pinia?
來源:Net Ninja 約 4 分鐘
短片對齊心智模型:為什麼不用 Vuex、store 裡放什麼。後面還有 getters、actions,見 播放清單。