86
Vue 3 學習之旅
狀態管理

Day 86: 官方狀態管理:Pinia

·6 分鐘閱讀·狀態管理

摘要

Pinia 是 Vue 官方推薦的、下一代輕量級狀態管理庫。它用於在整個應用程式中,以集中化的方式管理可以跨元件共享的狀態。

定義與說明

當多個元件需要共享同一份資料時(例如使用者登入資訊、購物車內容),如果僅靠 props 和 emits 會導致通訊變得非常複雜。Pinia 提供了一個集中式的「Store」,讓任何元件都可以讀取或修改這份共享狀態,且所有變更都是響應式的。

實作範例

stores/counter.js
// stores/counter.js
import { defineStore } from 'pinia';

export const useCounterStore = defineStore('counter', {
  state: () => ({ count: 0 }),
  actions: {
    increment() {
      this.count++;
    },
  },
});
MyComponent.vue
<!-- MyComponent.vue -->
<script setup>
import { useCounterStore } from '@/stores/counter';
const counter = useCounterStore();
</script>
<template>
  <button @click="counter.increment">計數: {{ counter.count }}</button>
</template>

結論

Pinia 以其極簡的 API、完整的 TypeScript 支援和優秀的開發者工具整合,成為了 Vue 3 狀態管理的首選方案,有效解決了複雜應用的狀態共享難題。

Pinia 狀態管理 響應式