Skip to content
Grok

Component State

State ภายใน component (เรียกว่า local state) เป็นข้อมูลที่ใช้งานเฉพาะใน component นั้นๆ

ts
<script setup lang="ts">
  // ประกาศ state ด้วย reactive import {ref} from 'vue'

  const count = ref(0) // สร้าง reactive state
</script>;

Global State

Global state เป็นข้อมูลที่แชร์ระหว่างหลาย components

ts
// ใช้ Pinia สำหรับ global state
import { defineStore } from "pinia";

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

Reactivity

Vue ใช้ระบบ reactivity เพื่อติดตามการเปลี่ยนแปลงของ state

FeatureDescription
ref()ใช้สำหรับ primitive values
reactive()ใช้สำหรับ objects
computed()สร้าง derived state

Best Practices

เคล็ดลับการจัดการ state ที่ดี

  1. ใช้ local state เมื่อข้อมูลใช้เฉพาะใน component
  2. ใช้ global state เมื่อต้องแชร์ข้อมูลระหว่าง components
  3. หลีกเลี่ยงการ mutate state โดยตรง ใช้ methods แทน