Setup store dùng đúng cú pháp setup(): ref là state, computed là getter, function là action.
Cuối hàm phải return những gì muốn công khai.
export const useCartStore = defineStore('cart', () => {
const items = ref<Item[]>([])
const total = computed(() => items.value.reduce((s, i) => s + i.price, 0))
async function load() {
items.value = await fetchCart()
}
return { items, total, load }
})So với option store ({ state, getters, actions }):
- Linh hoạt hơn: dùng được watch, composable khác, hoặc tạo biến private (khai báo nhưng không return).
- Đổi lại, mất một số tiện ích tự động: $reset() không có sẵn — phải tự viết action reset() gán lại giá trị ban đầu. Một vài plugin dựa trên state khai báo kiểu option cũng cần xử lý thêm.
- Bắt buộc return mọi state cần dùng, nếu quên thì devtools và SSR serialize không thấy.
Dù dùng kiểu nào, khi lấy state ra ngoài component vẫn phải storeToRefs(store) cho state/getter (action thì destructure thẳng được).