Back
VueMediumNew
How do you define and use a Pinia store with the Composition API syntax?
defineStore with a setup function
Ideal Answer
Pinia supports a 'setup store' syntax that mirrors setup() in components, using ref/computed/functions instead of state/getters/actions options:
JavaScript
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
export const useCounterStore = defineStore('counter', () => {
const count = ref(0)
const doubled = computed(() => count.value * 2)
function increment() { count.value++ }
return { count, doubled, increment }
})
Used in a component:
JavaScript
import { useCounterStore } from '@/stores/counter'
const store = useCounterStore()
store.increment()
Note: to keep reactivity when destructuring store properties, use storeToRefs(store).