Dark mode
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
Feature | Description |
---|---|
ref() | ใช้สำหรับ primitive values |
reactive() | ใช้สำหรับ objects |
computed() | สร้าง derived state |
Best Practices
เคล็ดลับการจัดการ state ที่ดี
- ใช้ local state เมื่อข้อมูลใช้เฉพาะใน component
- ใช้ global state เมื่อต้องแชร์ข้อมูลระหว่าง components
- หลีกเลี่ยงการ mutate state โดยตรง ใช้ methods แทน