5 min read
•Question 14 of 37mediumWhat is Pinia for state management?
Modern state management for Vue.
What You'll Learn
- Creating stores
- Using stores
- Actions and getters
Create a Store
code.jsJavaScript
// stores/counter.js
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0,
name: 'Counter'
}),
getters: {
doubleCount: (state) => state.count * 2
},
actions: {
increment() {
this.count++
},
async fetchCount() {
const res = await fetch('/api/count')
this.count = await res.json()
}
}
})Setup Store Syntax
code.jsJavaScript
export const useCounterStore = defineStore('counter', () => {
const count = ref(0)
const doubleCount = computed(() => count.value * 2)
function increment() {
count.value++
}
return { count, doubleCount, increment }
})Using in Components
code.txtVUE
<script setup>
import { useCounterStore } from '@/stores/counter'
import { storeToRefs } from 'pinia'
const store = useCounterStore()
// Destructure with reactivity
const { count, doubleCount } = storeToRefs(store)
// Actions can be destructured directly
const { increment } = store
</script>
<template>
<p>{{ count }} x 2 = {{ doubleCount }}</p>
<button @click="increment">+</button>
</template>