iT邦幫忙

2025 iThome 鐵人賽

DAY 27
0
Vue.js

新手學習Vue.js與實作之旅系列 第 27

Day27 Vue 狀態管理 Pinia

  • 分享至 

  • xImage
  •  

隨著開發的專案擴大,導致元件之間需要頻繁共享資料,若只依靠 props 或 emit 傳遞會讓程式變得複雜、難以維護,因此透過使用狀態管理工具來集中管理共享資料,便可以改善上述的問題。

Pinia 是什麼?

Pinia 是 Vue 官方推薦的狀態管理工具,透過將需要共享的資料放在 store 裡,使得任何元件都能輕鬆取用或更新,讓程式碼更乾淨也有利於維護。

安裝 Pinia

1.打開終端機,切換到想建立專案的資料夾(例如桌面),輸入 npm init vue@latest,表示建立一個新的Vue專案,之後自訂專案名稱並選擇要包含 Pinia 的功能,最後在指定的資料夾內就會出現新建的資料夾。
https://ithelp.ithome.com.tw/upload/images/20250930/20169120ESKcEuyOXS.png
https://ithelp.ithome.com.tw/upload/images/20250930/20169120COXTb3dNuh.png
2.依序輸入上圖的綠色字指令(cd自訂的專案名稱、npm install、npm run dev),之後就會跳出以下畫面。
https://ithelp.ithome.com.tw/upload/images/20250930/20169120lhs05sbRiW.png
3.按下 ctrl 鍵點選上圖中的 Local 網址,就會出現成功創建的畫面,之後就可以在 VS Code 開啟剛才新建的資料夾。
https://ithelp.ithome.com.tw/upload/images/20250930/201691207K31WHbPLc.png

Pinia 如何使用?

1. 定義 store

在 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 }
})

2. 定義 state、getter、action

  • state

    相當於元件中的 ref( )
  • getter

    相當於元件中的 computed( )
  • action

    相當於元件中的 method

3.在元件中調用 store

在元件中透過使用 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


上一篇
Day26 Vue Router (III)
下一篇
Day28 實作 Quiz (I)
系列文
新手學習Vue.js與實作之旅30
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言