Vue3 Fundamentals ยท State Management with Pinia

Setup stores

writing a store with the setup syntax

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.

  1. A setup store passes a function as the second argument to `defineStore`.
  2. In a setup store, a `ref` becomes state and a `computed` becomes a ___.
  3. In a setup store you must return the state, getters, and actions you want to expose.
  4. In a setup store, a plain function that changes state is an ___.
  5. A setup store cannot call other composables inside its body.