Setup stores
The options syntax groups state, getters, and actions into three keys. If
you already think in the Composition API, a setup store lets you write the
same store as a function.
You pass defineStore an id and a function instead of an options object. Inside,
ref declares state, computed declares a getter, and a plain function is an
action. Return everything you want to expose:
import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
export const useCounterStore = defineStore('counter', () => {
const count = ref(0);
const double = computed(() => count.value * 2);
function increment() {
count.value += 1;
}
return { count, double, increment };
});
The mapping is direct: a ref is state, a computed is a getter, and a function
is an action. Because the body is a setup function, you can also call other
composables inside it.
The one rule to remember is the return. Unlike <script setup>, a setup store
does not expose everything automatically โ anything you leave out of the returned
object is private.
You are about to answer a short quiz on setup stores.