Skip to main content

pinia

在你的 Vue 3 專案中安裝和設定 Pinia 是一個簡單的步驟,以下是完整的流程:

✅ 1. 安裝 Pinia 套件

打開終端機(Terminal)並在你的專案目錄中執行:

npm install pinia

如果你使用的是 yarn:

yarn add pinia

✅ 2. 設定 Pinia(main.js 或 main.ts)

打開你的 main.js 或 main.ts 檔案,並加入以下內容來註冊 Pinia:

import { createApp } from "vue";
import { createPinia } from "pinia";
import App from "./App.vue";

const app = createApp(App);

const pinia = createPinia();
app.use(pinia);

app.mount("#app");

✅ 3. 建立一個 Pinia Store

在 src/stores 目錄下建立一個 store,例如 counter.js(或 .ts):

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

export const useCounterStore = defineStore("counter", {
state: () => ({
count: 0,
}),
actions: {
increment() {
this.count++;
},
},
});

✅ 4. 在元件中使用 Store

<script setup>
import { useCounterStore } from '@/stores/counter'

const counter = useCounterStore()
</script>

<template>
<div>
<p>Count: {{ counter.count }}</p>
<button @click="counter.increment">Increment</button>
</div>
</template>
caution

拿取 getters 的值時,不要用解構賦值

const { deviceList } = useDeviceStore(); // 這樣會失去響應性!

應該直接用 deviceStore.deviceList