依狀態的使用範圍選擇 props、事件、provide 或 Pinia,並練習 storeToRefs。
適用:Vue 3.5 的單檔元件與 Composition API。先依
第 00 章
建立 Vite 專案;除另有指定,範例取代 src/App.vue。
先判斷資料屬於誰
單一輸入欄的展開狀態留在元件;父子共同使用資料採 props / emit;同一子樹的主題或表單服務採 provide / inject;跨頁面的購物車與登入資訊採 Pinia。並非所有狀態都需要全域化,資料生命週期應先於工具選擇。
最小共享狀態
在第 00 章的 src/main.js 加入 Pinia:
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
createApp(App).use(createPinia()).mount('#app')建立 src/stores/counter.js:
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', {
state: () => ({ count: 0 }),
getters: { doubled: state => state.count * 2 },
actions: { increment() { this.count++ } }
})src/App.vue:
<script setup>
import { storeToRefs } from 'pinia'
import { useCounterStore } from './stores/counter.js'
const store = useCounterStore()
const { count, doubled } = storeToRefs(store)
</script>
<template>
<p>{{ count }} / {{ doubled }}</p><button @click="store.increment">共享計數加一</button>
</template>按兩次顯示 2 / 4。另一個元件呼叫相同 store 會拿到同一份狀態。state/getter 直接解構會失去連動,使用 storeToRefs;action 可以直接解構。
訂閱與儲存
$subscribe 適合監看 store 修改,但 localStorage 可能被停用、容量不足或 JSON 損壞,持久化須有 try/catch 與版本遷移。不要儲存 access token 等敏感資料來示範便利性。非同步 action 要處理 loading、錯誤和重複呼叫,第 26 章給出本地資料示例。
冒險者留言
comments powered by Disqus