Javascript is required
·
1 min read

Pinia Tip: Use Setup Stores for More Flexibility

Pinia Tip: Use Setup Stores for More Flexibility Image

Besides Option Stores you can also use Setup Stores to define stores in Pinia. They bring more flexibility as you can create watchers within a store and freely use any composable.

Defining Setup Store

Just like the setup function in the Vue Composition API, a function that sets up reactive properties and methods can be passed, which will return an object containing the properties and methods that should be made available:

useCounterStore.js
1export const useCounterStore = defineStore('counter', () => {
2  const count = ref(0)
3
4  const doubleCount = computed(() => count.value * 2)
5
6  function increment() {
7    count.value++
8  }
9
10  return { count, doubleCount, increment }
11})

In Setup Stores:

  • ref()s become state properties
  • computed()s become getters
  • function()s become actions

What syntax should I pick?

When it comes to Vue's Composition API and Options API, select the one that you are most familiar with. If you are uncertain, start with the Option Stores.

Using Setup Store

At this point, we only defined the store but it won't be created until use...Store() is called inside of setup():

Component.vue
1<script setup>
2const store = useCounterStore()
3</script>
4
5<template>
6  <span>Counter: {{ store.count }}</span>
7  <span>Double Count: {{ store.doubleCount }}</span>
8  <button @click="store.increment">Increment</button>
9</template>

Info

The store object has been wrapped with reactive, so there is no need to include .value when using getters, but similar to props in setup, it cannot be destructured. You need to use storeToRefs() to destructure while keeping reactivity.

Bonus Tip

You can use composables that return writable state like VueUse useLocalStorage() directly within the state() function:

useCounterStore.js
1export const useCounterStore = defineStore('counter', () => {
2  const counterInfo = useLocalStorage('counterInfo', null)
3
4  return { counterInfo }
5})

The same example using Option Store:

useCounterStore.js
1export const useCounterStore = defineStore('counter', () => {
2  state: () => ({
3    // ...
4    counterInfo: useLocalStorage('counterInfo', null),
5  })
6})

If you liked this Vue tip, follow me on X to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter:

I will never share any of your personal data. You can unsubscribe at any time.