# Vue3 pinia ## 請解釋Pinia pinia 是Vue的狀態管理庫 他是一個集中式儲存狀態的方式 讓多個元件可以共享、讀取、更新資料狀態 Pinia有支援 熱模組(Hot Module Replacement) 機制, 資料更新的時候,不需要重新載入整個網頁,僅即時更新單一模組(例如一個元件) ![image](https://hackmd.io/_uploads/BkuJIm8gee.png) 📦 使用 Composition API 風格的 Pinia store 當你使用 defineStore 時,第二個參數可以是 setup 函數,這樣你就能夠利用 Composition API 的風格來創建 store。這種寫法讓你能夠像在 Vue 組件中一樣使用 ref、computed、reactive 等 API。 🧠 範例:使用 Composition API 的 Pinia store 以下是如何在 Pinia 中使用 Composition API 寫法定義一個 user store 的範例: ```js! // stores/user.js import { defineStore } from 'pinia' import { ref, computed } from 'vue' export const useUserStore = defineStore('user', () => { // 定義 state const name = ref('Alice') const age = ref(30) // 定義 getter const isAdult = computed(() => age.value >= 18) // 定義 actions const updateName = (newName) => { name.value = newName } const incrementAge = () => { age.value++ } // 返回 state, getter 和 actions return { name, age, isAdult, updateName, incrementAge } }) ```