Настройка State Management (Pinia) для Vue-додатку
Pinia — офіційний state management для Vue 3. Простий API подібний до Zustand, побудований на composition API, повна підтримка TypeScript. Сторі визначаються як composables, не потрібні окремі файли або boilerplate.
Замінює Vuex як рекомендоване рішення управління станом для Vue 3.
Що входить у роботу
Створення сторів з Pinia, організація стану, екшнів та гетерів, інтеграція з Vue Router, настройка devtools, тестування сторів.
Встановлення
npm install pinia
Настройка у main.ts:
import { createPinia } from 'pinia'
const app = createApp(App)
app.use(createPinia())
Базовий стор
import { defineStore } from 'pinia'
export const useCartStore = defineStore('cart', {
state: () => ({
items: [] as CartItem[],
}),
getters: {
total: (state) => state.items.reduce((sum, i) => sum + i.price * i.qty, 0),
count: (state) => state.items.reduce((sum, i) => sum + i.qty, 0),
},
actions: {
addItem(item: CartItem) {
const existing = this.items.find(i => i.id === item.id)
if (existing) {
existing.qty++
} else {
this.items.push({ ...item, qty: 1 })
}
},
},
})
Використання у компонентах:
<script setup>
const cart = useCartStore()
</script>
<template>
<div>
<button @click="cart.addItem(product)">У кошик ({{ cart.count }})</button>
<span>Всього: {{ cart.total }}</span>
</div>
</template>
Терміни
Базова настройка Pinia — 1 година. Кілька сторів з екшнами — 1–2 години. Повна інтеграція з Vue Router — 2–3 години.







