Dark mode
Store ใน Vue 3 (Pinia)
ปัญหาการแชร์ state ระหว่าง component
- เมื่อแอปใหญ่ขึ้น การส่งข้อมูลระหว่าง component หลายชั้น (props, emit) จะซับซ้อน
- ต้องการ state กลางที่ทุก component เข้าถึงได้
Store คืออะไร?
- Store คือที่เก็บ state กลางของแอป เช่น Pinia (Vuex รุ่นใหม่)
- ทุก component สามารถอ่าน/เปลี่ยนแปลง state ได้จาก store เดียวกัน
- Store สามารถเก็บ state, getter, action (method เปลี่ยน state)
ตัวอย่างการสร้าง Store ด้วย Pinia
- ติดตั้ง Pinia
bash
npm install pinia
- สร้าง store (เช่น useCounterStore)
ts
// stores/counter.ts
import { defineStore } from "pinia";
export const useCounterStore = defineStore("counter", {
state: () => ({ count: 0 }),
getters: {
double: (state) => state.count * 2,
},
actions: {
increment() {
this.count++;
},
},
});
- ใช้ store ใน component
vue
<script setup lang="ts">
import { useCounterStore } from "@/stores/counter";
const counter = useCounterStore();
</script>
<template>
<button @click="counter.increment">{{ counter.count }}</button>
<p>Double: {{ counter.double }}</p>
</template>
เปรียบเทียบ Store กับ ref/reactive
จุดเด่น | ref/reactive | Store (Pinia) |
---|---|---|
Scope | ใน component เดียว | ทุก component |
การแชร์ข้อมูล | ต้องส่ง props/emit | ทุกที่เข้าถึงได้ง่าย |
การจัดการ state | ง่าย, เหมาะกับ local | เหมาะกับ global/ซับซ้อน |
Devtools | รองรับน้อยกว่า | Devtools รองรับดีมาก |
สรุปและแนวทางเลือกใช้
- ถ้า state ใช้เฉพาะใน component เดียว ใช้ ref/reactive
- ถ้า state ต้องแชร์ข้ามหลาย component หรือแอปซับซ้อน ใช้ Store (Pinia)
- Pinia ใช้งานง่าย รองรับ TypeScript และ Devtools ดีมาก