Pinia — Official Vue.js State Management
You are an expert in Pinia, the official state management library for Vue.js. You help developers build Vue applications with type-safe stores, Composition API support, getters (computed), actions (sync and async), plugins, SSR compatibility, and Vue DevTools integration — replacing Vuex with a simpler, fully typed, modular store system.
Core Capabilities
Store Definition
// stores/auth.ts
import { defineStore } from "pinia";
import { ref, computed } from "vue";
// Setup Store (Composition API style)
export const useAuthStore = defineStore("auth", () => {
const user = ref<User | null>(null);
const token = ref<string | null>(localStorage.getItem("token"));
const isLoading = ref(false);
// Getters (computed)
const isAuthenticated = computed(() => !!token.value);
const isAdmin = computed(() => user.value?.role === "admin");
// Actions
async function login(email: string, password: string) {
isLoading.value = true;
try {
const response = await api.post("/auth/login", { email, password });
token.value = response.data.token;
user.value = response.data.user;
localStorage.setItem("token", token.value!);
} finally {
isLoading.value = false;
}
}
function logout() {
token.value = null;
user.value = null;
localStorage.removeItem("token");
}
async function fetchProfile() {
if (!token.value) return;
user.value = await api.get("/auth/profile");
}
return { user, token, isLoading, isAuthenticated, isAdmin, login, logout, fetchProfile };
});
// Option Store style (familiar to Vuex users)
export const useCartStore = defineStore("cart", {
state: () => ({
items: [] as CartItem[],
}),
getters: {
total: (state) => state.items.reduce((sum, i) => sum + i.price * i.qty, 0),
itemCount: (state) => state.items.reduce((sum, i) => sum + i.qty, 0),
},
actions: {
addItem(product: Product) {
const existing = this.items.find(i => i.id === product.id);
if (existing) existing.qty++;
else this.items.push({ ...product, qty: 1 });
},
removeItem(id: string) {
this.items = this.items.filter(i => i.id !== id);
},
async checkout() {
await api.post("/orders", { items: this.items });
this.items = [];
},
},
});
Usage in Components
<script setup lang="ts">
import { useAuthStore } from "@/stores/auth";
import { useCartStore } from "@/stores/cart";
import { storeToRefs } from "pinia";
const auth = useAuthStore();
const cart = useCartStore();
// storeToRefs preserves reactivity for destructured state/getters
const { user, isAuthenticated } = storeToRefs(auth);
const { total, itemCount } = storeToRefs(cart);
</script>
<template>
<nav>
<span v-if="isAuthenticated">{{ user?.name }}</span>
<button v-else @click="auth.login(email, password)">Login</button>
<span>Cart ({{ itemCount }}): ${{ total.toFixed(2) }}</span>
</nav>
</template>
Installation
npm install pinia
// main.ts
import { createPinia } from "pinia";
app.use(createPinia());
Best Practices
- Setup stores — Prefer Composition API style (
ref, computed); full TypeScript inference without extra types
- storeToRefs — Use
storeToRefs(store) when destructuring; plain destructure breaks reactivity
- One store per domain — Separate auth, cart, ui stores; avoid a single monolithic store
- Actions for async — Put API calls in actions; components stay clean, logic is reusable and testable
- Getters for derived — Use computed/getters for filtered lists, totals, formatted values; auto-cached
- Plugins — Use plugins for persistence (
pinia-plugin-persistedstate), logging, or shared behaviors
- Store composition — Import other stores inside a store:
const auth = useAuthStore(); explicit dependencies
- DevTools — Pinia integrates with Vue DevTools; inspect state, time-travel, edit state in real-time
1---2name: pinia3description: >-4 You are an expert in Pinia, the official state management library for5 Vue.js. You help developers build Vue applications with type-safe stores,6 Composition API support, getters (computed), actions (sync and async),7 plugins, SSR compatibility, and Vue DevTools integration — replacing Vuex8 with a simpler, fully typed, modular store system.9license: Apache-2.010compatibility: ''11metadata:12 source: https://skillmd.com/skills/eliferjunior/pinia13 author: terminal-skills14 version: 1.0.015 category: Frontend Development16 tags:17 - vue18 - state-management19 - typescript20 - composition-api21 - store22 - devtools23---2425# Pinia — Official Vue.js State Management2627You are an expert in Pinia, the official state management library for Vue.js. You help developers build Vue applications with type-safe stores, Composition API support, getters (computed), actions (sync and async), plugins, SSR compatibility, and Vue DevTools integration — replacing Vuex with a simpler, fully typed, modular store system.2829## Core Capabilities3031### Store Definition3233```typescript34// stores/auth.ts35import { defineStore } from "pinia";36import { ref, computed } from "vue";3738// Setup Store (Composition API style)39export const useAuthStore = defineStore("auth", () => {40 const user = ref<User | null>(null);41 const token = ref<string | null>(localStorage.getItem("token"));42 const isLoading = ref(false);4344 // Getters (computed)45 const isAuthenticated = computed(() => !!token.value);46 const isAdmin = computed(() => user.value?.role === "admin");4748 // Actions49 async function login(email: string, password: string) {50 isLoading.value = true;51 try {52 const response = await api.post("/auth/login", { email, password });53 token.value = response.data.token;54 user.value = response.data.user;55 localStorage.setItem("token", token.value!);56 } finally {57 isLoading.value = false;58 }59 }6061 function logout() {62 token.value = null;63 user.value = null;64 localStorage.removeItem("token");65 }6667 async function fetchProfile() {68 if (!token.value) return;69 user.value = await api.get("/auth/profile");70 }7172 return { user, token, isLoading, isAuthenticated, isAdmin, login, logout, fetchProfile };73});7475// Option Store style (familiar to Vuex users)76export const useCartStore = defineStore("cart", {77 state: () => ({78 items: [] as CartItem[],79 }),80 getters: {81 total: (state) => state.items.reduce((sum, i) => sum + i.price * i.qty, 0),82 itemCount: (state) => state.items.reduce((sum, i) => sum + i.qty, 0),83 },84 actions: {85 addItem(product: Product) {86 const existing = this.items.find(i => i.id === product.id);87 if (existing) existing.qty++;88 else this.items.push({ ...product, qty: 1 });89 },90 removeItem(id: string) {91 this.items = this.items.filter(i => i.id !== id);92 },93 async checkout() {94 await api.post("/orders", { items: this.items });95 this.items = [];96 },97 },98});99```100101### Usage in Components102103```vue104<script setup lang="ts">105import { useAuthStore } from "@/stores/auth";106import { useCartStore } from "@/stores/cart";107import { storeToRefs } from "pinia";108109const auth = useAuthStore();110const cart = useCartStore();111112// storeToRefs preserves reactivity for destructured state/getters113const { user, isAuthenticated } = storeToRefs(auth);114const { total, itemCount } = storeToRefs(cart);115</script>116117<template>118 <nav>119 <span v-if="isAuthenticated">{{ user?.name }}</span>120 <button v-else @click="auth.login(email, password)">Login</button>121 <span>Cart ({{ itemCount }}): ${{ total.toFixed(2) }}</span>122 </nav>123</template>124```125126## Installation127128```bash129npm install pinia130```131132```typescript133// main.ts134import { createPinia } from "pinia";135app.use(createPinia());136```137138## Best Practices1391401. **Setup stores** — Prefer Composition API style (`ref`, `computed`); full TypeScript inference without extra types1412. **storeToRefs** — Use `storeToRefs(store)` when destructuring; plain destructure breaks reactivity1423. **One store per domain** — Separate auth, cart, ui stores; avoid a single monolithic store1434. **Actions for async** — Put API calls in actions; components stay clean, logic is reusable and testable1445. **Getters for derived** — Use computed/getters for filtered lists, totals, formatted values; auto-cached1456. **Plugins** — Use plugins for persistence (`pinia-plugin-persistedstate`), logging, or shared behaviors1467. **Store composition** — Import other stores inside a store: `const auth = useAuthStore()`; explicit dependencies1478. **DevTools** — Pinia integrates with Vue DevTools; inspect state, time-travel, edit state in real-time