Skip to content

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

  1. ติดตั้ง Pinia
bash
npm install pinia
  1. สร้าง 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++;
    },
  },
});
  1. ใช้ 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/reactiveStore (Pinia)
Scopeใน component เดียวทุก component
การแชร์ข้อมูลต้องส่ง props/emitทุกที่เข้าถึงได้ง่าย
การจัดการ stateง่าย, เหมาะกับ localเหมาะกับ global/ซับซ้อน
Devtoolsรองรับน้อยกว่าDevtools รองรับดีมาก

สรุปและแนวทางเลือกใช้

  • ถ้า state ใช้เฉพาะใน component เดียว ใช้ ref/reactive
  • ถ้า state ต้องแชร์ข้ามหลาย component หรือแอปซับซ้อน ใช้ Store (Pinia)
  • Pinia ใช้งานง่าย รองรับ TypeScript และ Devtools ดีมาก