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 :
ref()
s become state properties.computed()
s become getters.function()
s become actions.
</aside>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 }
})
<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>
export const useCounterStore = defineStore('counter', () => {
// States
const count = ref(0) // [!code hl]
return { count }
})
<script setup>
const store = useCounterStore()
console.log(store.count)
</script>
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
}
})
We use $patch
method for mutating the state.
<template>
<button @click="store.$patch({ count: 12 })">patch</button>
</template>
<template>
<button @click="store.$state = { count: 12 }">Replace</button>
</template>