Pinia is a store library for Vue which allows you to share a state across components.

<aside> ☝

We have used Composition API in this cheatsheet as it is recommended.

</aside>

<aside> ℹ️

In Setup Stores :

Define Store

export const useCounterStore = defineStore('counter', () => {

  // States
  const count = ref(0)
  const name = ref('Eduardo')

  // Getters
  const doubleCount = computed(() => count.value * 2)

  // Actions
  function increment() {
    count.value++
  }

  return { count, name, doubleCount, increment }
})

Use store

<script setup>
import { useCounterStore } from '@/stores/counter'

// access the `store` variable anywhere in the component ✨
const store = useCounterStore()

// Another way to use the store
// Destructuring from the store

// This will also extract refs for properties added by plugins
// but skip any action or non reactive (non ref/reactive) property
const { name, doubleCount } = storeToRefs(store)

// the increment action can just be destructured
const { increment } = store

</script>

States

Define a state

export const useCounterStore = defineStore('counter', () => {
  // States
  const count = ref(0) // [!code hl]

  return { count }
})

Accessing the States

<script setup>
  const store = useCounterStore()
  console.log(store.count)
</script>

Resetting the States

In Setup Stores, you need to create your own $reset() method

export const useCounterStore = defineStore('counter', () => {
    const count = ref(0)

    function $reset() {
    count.value = 0
    }
})

Mutating the state

We use $patch method for mutating the state.

<template>
    <button @click="store.$patch({ count: 12 })">patch</button>
</template>

Replacing the state

<template>
    <button @click="store.$state = { count: 12 }">Replace</button>
</template>