vue-pinia
БесплатноБез исполняемых скриптовНе проверенVue 3 state management with Pinia using the Composition API, covering setup stores, SSR/Nuxt integration, persistence, and testing. Use when creating or…
от Mindrally★ 323 звезды на GitHubОб этом скилле
Vue + Pinia
Pinia is the standard state management library for Vue 3, and setup stores built with the Composition API give shared application state the same ergonomics as local ref/computed state.
Workflow for Adding a Pinia Store
- Decide if Pinia is the right tool — Confirm the state is shared across routes/components, not server cache data, and not purely local UI state (see State Ownership below).
- Create the store file — Add one file per domain under
stores/, e.g.stores/cart.ts, usingdefineStore('cart', () => { ... }). - Define state, getters, and actions — Declare state with
ref/reactive, derive values withcomputed, and put all writes/side effects in functions (actions). - Return everything from the setup function — Return every piece of state, every getter, and every action so Pinia devtools, SSR, and plugins can track them.
- Consume in components — Call the store at the top of
<script setup>, destructure reactive state withstoreToRefs(), and destructure actions directly. - Handle SSR/router-guard usage — Call the store from inside setup, a getter, an action, or pass the active Pinia instance explicitly outside setup contexts.
- Add persistence and tests — Allowlist persisted fields, validate rehydrated data, and test actions directly with
@pinia/testing.
State Ownership
- Keep component-only state in the component with
ref,reactive, orcomputed. - Use Pinia for shared client state that spans routes, layouts, or unrelated component trees.
- Use route params and query strings for shareable navigation state — don't duplicate it into a store.
- Use Nuxt
useFetch/useAsyncData, TanStack Query for Vue, or the existing API layer for server state — Pinia is for client state, not a data-fetching cache. - Do not copy server cache data into Pinia unless it is an intentional editable draft, offline cache, or workflow snapshot with its own lifecycle.
Store Structure
- Prefer setup stores with
defineStore('name', () => { ... })for Vue 3 Composition API projects over the older options-APIdefineStore({ state, getters, actions })form. - Use one store file per domain under
stores/, such asstores/cart.tsorstores/session.ts. - Keep state, computed getters, and actions together when they represent one cohesive domain.
- Return every state property from setup stores so Pinia can track it for devtools, SSR, and plugins — an un-returned
refis invisible to the rest of the system. - Keep getters pure and side-effect free; put writes, I/O, and orchestration in actions.
// stores/cart.ts
import { computed, ref } from 'vue'
import { defineStore } from 'pinia'
interface CartLine {
id: string
name: string
quantity: number
unitPrice: number
}
export const useCartStore = defineStore('cart', () => {
const lines = ref<CartLine[]>([])
const itemCount = computed(() =>
lines.value.reduce((total, line) => total + line.quantity, 0),
)
const subtotal = computed(() =>
lines.value.reduce((total, line) => total + line.quantity * line.unitPrice, 0),
)
function addLine(line: CartLine) {
const existing = lines.value.find((item) => item.id === line.id)
if (existing) {
existing.quantity += line.quantity
return
}
lines.value.push(line)
}
function removeLine(id: string) {
lines.value = lines.value.filter((line) => line.id !== id)
}
function clearCart() {
lines.value = []
}
return {
lines,
itemCount,
subtotal,
addLine,
removeLine,
clearCart,
}
})
Component Usage
- Call stores at the top of
<script setup>or inside setup functions, getters, and actions — never conditionally, and never inside a plain.js/.tsmodule loaded at import time. - Use
storeToRefs()when destructuring store state or getters in components, so reactivity is preserved. - Destructure actions directly when useful; actions remain bound to the store and don't need
storeToRefs(). - Avoid writing large business workflows in components; move them to store actions or composables so they're testable and reusable.
- Prefer computed values over watchers when deriving state — a
watchthat just recomputes a value should usually be acomputed.
<script setup lang="ts">
import { storeToRefs } from 'pinia'
import { useCartStore } from '@/stores/cart'
const cart = useCartStore()
const { itemCount, subtotal } = storeToRefs(cart)
const { clearCart } = cart
</script>
<template>
<div>
<p>{{ itemCount }} items — ${{ subtotal.toFixed(2) }}</p>
<button type="button" :disabled="itemCount === 0" @click="clearCart">
Clear cart
</button>
</div>
</template>
TypeScript
- Type store state, action payloads, and API responses explicitly.
- Avoid
any; useunknownand narrow external inputs (API responses, persisted storage) before committing them to state. - Use interfaces for object state that is shared across components o
Установить vue-pinia в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл vue-pinia?
Vue 3 state management with Pinia using the Composition API, covering setup stores, SSR/Nuxt integration, persistence, and testing. Use when creating or refactoring Pinia stores, deciding what state belongs in a store versus a component, wiring stores into router guards, persisting store state to storage, or testing store actions with @pinia/testing.
Как установить скилл vue-pinia?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл vue-pinia запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic