隨著開發的專案擴大,導致元件之間需要頻繁共享資料,若只依靠 props 或 emit 傳遞會讓程式變得複雜、難以維護,因此透過使用狀態管理工具來集中管理共享資料,便可以改善上述的問題。
Pinia 是 Vue 官方推薦的狀態管理工具,透過將需要共享的資料放在 store 裡,使得任何元件都能輕鬆取用或更新,讓程式碼更乾淨也有利於維護。
1.打開終端機,切換到想建立專案的資料夾(例如桌面),輸入 npm init vue@latest,表示建立一個新的Vue專案,之後自訂專案名稱並選擇要包含 Pinia 的功能,最後在指定的資料夾內就會出現新建的資料夾。
2.依序輸入上圖的綠色字指令(cd自訂的專案名稱、npm install、npm run dev),之後就會跳出以下畫面。
3.按下 ctrl 鍵點選上圖中的 Local 網址,就會出現成功創建的畫面,之後就可以在 VS Code 開啟剛才新建的資料夾。
在 src 資料夾下創建 stores 資料夾,並在裡面新增自訂的 js 檔案,例如:counter.js ,在 js 檔案裡寫入 import { defineStore } from 'pinia' 來定義 store,之後再寫入自訂的 store 名稱,例如:useCounterStore。
P.S.若以上述方法安裝 Pinia ,在 src 資料夾下的 stores/counter.js 有定義預設的程式碼(如下),
此外定義 store 有 Option Store 和 Setup Store 兩種寫法,此篇文章將使用Setup Store。
import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', () => {
const count = ref(0)
const doubleCount = computed(() => count.value * 2)
function increment() {
count.value++
}
return { count, doubleCount, increment }
})
在元件中透過使用 import 來匯入 store 並創建實例,就可以在元件中調用 store 的資料。
<script setup>
import { useCounterStore } from '@/stores/counter'
const counter = useCounterStore()
// 使用 state
console.log(counter.count)
// 使用 getter
console.log(counter.doubleCount)
// 使用 action
counter.increment()
</script>
<template>
<div>
<p>計數: {{ counter.count }}</p>
<p>雙倍: {{ counter.doubleCount }}</p>
<button @click="counter.increment()">增加</button>
</div>
</template>
https://zh-hk.vuejs.org/guide/scaling-up/state-management.html
https://pinia.vuejs.org/zh/introduction.html
https://ithelp.ithome.com.tw/articles/10316570
https://ithelp.ithome.com.tw/articles/10316571
https://vocus.cc/article/654a5302fd897800015d7dd9
https://ithelp.ithome.com.tw/m/articles/10306919
https://ithelp.ithome.com.tw/articles/10338971