iT邦幫忙

2025 iThome 鐵人賽

DAY 20
0
Vue.js

邊學邊做:Vue.js 實戰養成計畫系列 第 20

Day 20:能量核心 — Pinia 狀態管理基礎

  • 分享至 

  • xImage
  •  

為什麼需要 Pinia?

在小專案裡,用 props 傳資料、emit 傳事件就夠。
但隨著專案變大,不同元件之間要共用資料(例如:玩家登入狀態、星艦燃料存量、背包物品),props 傳來傳去會變成災難。
⭢這時候就需要「全域資料倉庫」,Pinia 就是 Vue 3 官方推薦的能量核心。

步驟

  1. 安裝與設定
npm install pinia

2.在 main.js 掛上:

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

const app = createApp(App)
app.use(createPinia())
app.mount('#app')
  1. 建立一個 store
    Store 就像是一個能量核心,專門管理某一塊狀態。
    src/stores/ship.js:
import { defineStore } from 'pinia'

export const useShipStore = defineStore('ship', {
  state: () => ({
    fuel: 100,
    hp: 80,
    shield: true
  }),
  actions: {
    consumeFuel(amount) {
      this.fuel -= amount
    },
    repair() {
      this.hp = 100
    }
  },
  getters: {
    isDamaged: (state) => state.hp < 100
  }
})
  1. 在元件中使用
<script setup>
import { useShipStore } from '../stores/ship'

const ship = useShipStore()

function travel() {
  ship.consumeFuel(10)
}
</script>

<template>
  <div>
    <p>燃料:{{ ship.fuel }}</p>
    <p>血量:{{ ship.hp }}({{ ship.isDamaged ? '受損' : '完好' }})</p>
    <button @click="travel">🌌 啟航</button>
  </div>
</template>

結論

1.state → 儲存共享資料(像燃料槽)。
2.actions → 修改資料的方式(像操作控制台)。
3.getters → 基於 state 的計算屬性(像狀態燈號)。
4.store → 不同模組的能量核心,可在各元件隨時呼叫。
⭢Pinia 讓我們把狀態集中,避免資料在元件間傳來傳去,專案會更乾淨、邏輯更清楚。

參考資源
https://vuejs.org/guide
https://www.runoob.com/vue3


上一篇
Day 19:探索新維度 — Composition API
系列文
邊學邊做:Vue.js 實戰養成計畫20
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言