| name | pinia |
| description | Pinia state management for Vue 3. Use defineStore() with Composition API style (setup stores). Covers store definition, state, getters, actions, TypeScript, store composition, SSR, and best practices. |
| license | MIT |
| metadata | {"author":"github.com/belos-street","version":"1.0.0"} |
Pinia state management for Vue 3 using Composition API style stores.
Store Definition
State
Getters
Actions
TypeScript
Store Composition
Best Practices
Quick Reference
Basic Setup Store (Composition API)
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
export const useCounterStore = defineStore('counter', () => {
const count = ref(0)
const doubleCount = computed(() => count.value * 2)
function increment() {
count.value++
}
function $reset() {
count.value = 0
}
return { count, doubleCount, increment, $reset }
})
Using Store in Component
<script setup lang="ts">
import { useCounterStore } from '@/stores/counter'
const counter = useCounterStore()
</script>
<template>
<div>
<p>Count: {{ counter.count }}</p>
<p>Double: {{ counter.doubleCount }}</p>
<button @click="counter.increment">Increment</button>
</div>
</template>
Store with TypeScript
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
interface User {
id: number
name: string
email: string
}
export const useUserStore = defineStore('user', () => {
const user = ref<User | null>(null)
const isAuthenticated = computed(() => user.value !== null)
async function login(email: string, password: string) {
const response = await fetch('/api/login', {
method: 'POST',
body: JSON.stringify({ email, password })
})
user.value = await response.json()
}
function logout() {
user.value = null
}
return { user, isAuthenticated, login, logout }
})
Store Composition
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { useAuthStore } from './auth'
import { useCartStore } from './cart'
export const useCheckoutStore = defineStore('checkout', () => {
const authStore = useAuthStore()
const cartStore = useCartStore()
const isProcessing = ref(false)
async function checkout() {
if (!authStore.isAuthenticated) {
throw new Error('User not authenticated')
}
isProcessing.value = true
try {
await processPayment(cartStore.items)
cartStore.clear()
} finally {
isProcessing.value = false
}
}
return { isProcessing, checkout }
})
Key Imports
import { defineStore } from 'pinia'
import { createPinia } from 'pinia'
import { ref, reactive, computed, watch } from 'vue'
import { storeToRefs } from 'pinia'
import type { StoreDefinition } from 'pinia'
Installation
npm install pinia
yarn add pinia
pnpm add pinia
Setup in main.ts
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
const app = createApp(App)
const pinia = createPinia()
app.use(pinia)
app.mount('#app')