Back to Home

สอนใช้ Pinia จัดการ State ใน Vue 3: ตัวตายตัวแทน Vuex ที่ดีกว่า

Vue Developer18 ธันวาคม 2567State Management
VuePiniaState ManagementVue 3TypeScript

Pinia คือ State Management Library ที่แนะนำอย่างเป็นทางการสำหรับ Vue 3

สร้าง Store

// stores/counter.js import { defineStore } from 'pinia'; export const useCounterStore = defineStore('counter', { state: () => ({ count: 0, }), getters: { doubleCount: (state) => state.count * 2, }, actions: { increment() { this.count++; }, }, });

ใช้งาน Store

<script setup> import { useCounterStore } from '@/stores/counter'; const counter = useCounterStore(); </script> <template> <p>Count: {{ counter.count }}</p> <p>Double: {{ counter.doubleCount }}</p> <button @click="counter.increment">Increment</button> </template>

สรุป

Pinia มี API ที่เรียบง่ายกว่า Vuex, รองรับ TypeScript ได้ดีเยี่ยม และไม่มี Mutations ทำให้โค้ดสั้นลง