pinia-v3
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChinesePinia v3 - Vue State Management
Pinia v3 - Vue 状态管理
Status: Production Ready ✅
Last Updated: 2025-11-11
Dependencies: Vue 3 (or Vue 2.7 with @vue/composition-api)
Latest Versions: pinia@^3.0.4, @pinia/nuxt@^0.11.2, @pinia/testing@^1.0.2
状态:已就绪可用于生产环境 ✅
最后更新:2025-11-11
依赖:Vue 3(或搭配@vue/composition-api的Vue 2.7)
最新版本:pinia@^3.0.4, @pinia/nuxt@^0.11.2, @pinia/testing@^1.0.2
Quick Start (5 Minutes)
快速开始(5分钟)
1. Install Pinia
1. 安装Pinia
bash
bun add piniabash
bun add piniaor
or
bun add pinia
bun add pinia
or
or
bun add pinia
**For Vue <2.7 users**: Also install `@vue/composition-api` with `bun add @vue/composition-api`
**Why this matters:**
- Pinia is the official Vue state management library
- Provides better TypeScript support than Vuex
- Eliminates mutations and namespacing complexity
- Full DevTools support with time-travel debuggingbun add pinia
**对于Vue <2.7用户**:还需安装`@vue/composition-api`,执行`bun add @vue/composition-api`
**为什么这很重要**:
- Pinia是官方Vue状态管理库
- 比Vuex提供更完善的TypeScript支持
- 消除了mutations和命名空间的复杂性
- 支持完整的DevTools功能,包括时间旅行调试2. Create and Register Pinia Instance
2. 创建并注册Pinia实例
typescript
// main.ts
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
const pinia = createPinia()
const app = createApp(App)
app.use(pinia)
app.mount('#app')CRITICAL:
- Install Pinia BEFORE using any store
- Call before mounting the app
app.use(pinia) - Only one Pinia instance per application (unless SSR)
typescript
// main.ts
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
const pinia = createPinia()
const app = createApp(App)
app.use(pinia)
app.mount('#app')关键注意事项:
- 在使用任何仓库之前安装Pinia
- 在挂载应用前调用
app.use(pinia) - 每个应用只能有一个Pinia实例(SSR场景除外)
3. Define Your First Store
3. 定义你的第一个仓库
typescript
// stores/counter.ts
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0,
name: 'Eduardo'
}),
getters: {
doubleCount: (state) => state.count * 2
},
actions: {
increment() {
this.count++
}
}
})typescript
// stores/counter.ts
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0,
name: 'Eduardo'
}),
getters: {
doubleCount: (state) => state.count * 2
},
actions: {
increment() {
this.count++
}
}
})4. Use Store in Components
4. 在组件中使用仓库
vue
<script setup>
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>vue
<script setup>
import { useCounterStore } from '@/stores/counter'
const counter = useCounterStore()
</script>
<template>
<div>
<p>计数:{{ counter.count }}</p>
<p>双倍计数:{{ counter.doubleCount }}</p>
<button @click="counter.increment">增加</button>
</div>
</template>The Two Store Syntaxes
两种仓库语法
Load for complete comparison of Option vs Setup stores.
references/store-syntax-guide.md查看获取Option和Setup仓库的完整对比。
references/store-syntax-guide.mdQuick Overview
快速概述
Pinia supports two store definition syntaxes:
Option Stores:
- Similar to Vue Options API
- Built-in method
$reset() - Best for: Simpler use cases, teams familiar with Vuex
Setup Stores:
- Uses Composition API pattern
- Full composables integration
- Best for: Advanced patterns, need watchers/VueUse integration
→ Load for: Complete syntax comparison, examples, choosing criteria
references/store-syntax-guide.mdPinia支持两种仓库定义语法:
Option仓库:
- 类似Vue Options API
- 内置方法
$reset() - 最适用:简单场景、熟悉Vuex的团队
Setup仓库:
- 使用Composition API模式
- 支持完整的组合式函数集成
- 最适用:高级模式、需要观察者/VueUse集成的场景
→ 查看获取:完整语法对比、示例、选择标准
references/store-syntax-guide.mdState, Getters, and Actions
State、Getters和Actions
Load for complete API reference.
references/state-getters-actions.md查看获取完整API参考。
references/state-getters-actions.mdQuick Reference
快速参考
State:
- Define in (option) or
state: () => ({...})(setup)ref() - Access directly:
store.count - Mutate directly: or
store.count++store.$patch({...}) - Reset: (option stores only)
store.$reset()
Getters:
- Computed properties:
getters: { double: (state) => state.count * 2 } - Access other getters with (must type return value)
this
Actions:
- Business logic:
actions: { increment() { this.count++ } } - Can be async
- Access other stores directly
Store Destructuring:
typescript
import { storeToRefs } from 'pinia'
// ✅ For reactivity
const { name, count } = storeToRefs(store)
// ✅ Actions can destructure directly
const { increment } = store→ Load for: Complete API, subscriptions, store composition patterns, Options API usage
references/state-getters-actions.mdState:
- 在(Option语法)或
state: () => ({...})(Setup语法)中定义ref() - 直接访问:
store.count - 直接修改:或
store.count++store.$patch({...}) - 重置:(仅Option仓库支持)
store.$reset()
Getters:
- 计算属性:
getters: { double: (state) => state.count * 2 } - 使用访问其他getters(必须指定返回值类型)
this
Actions:
- 业务逻辑:
actions: { increment() { this.count++ } } - 支持异步
- 可直接访问其他仓库
仓库解构:
typescript
import { storeToRefs } from 'pinia'
// ✅ 保持响应式
const { name, count } = storeToRefs(store)
// ✅ Actions可直接解构
const { increment } = store→ 查看获取:完整API、订阅、仓库组合模式、Options API用法
references/state-getters-actions.mdPlugins and Composables
插件与组合式函数
Load for complete plugin and composables guide.
references/plugins-composables.md查看获取完整的插件和组合式函数指南。
references/plugins-composables.mdPlugin Basics
插件基础
typescript
pinia.use(({ store, options }) => {
// Add properties to every store
return { customProperty: 'value' }
})typescript
pinia.use(({ store, options }) => {
// 为所有仓库添加属性
return { customProperty: 'value' }
})Composables Integration
组合式函数集成
Option Stores: Limited to style in
Setup Stores: Full VueUse/composables support
useLocalStoragestate()→ Load for: Complete plugin patterns, VueUse integration, TypeScript typing, common patterns (persistence, router, logger)
references/plugins-composables.mdOption仓库:仅支持在中使用这类组合式函数
Setup仓库:完全支持VueUse/组合式函数
state()useLocalStorage→ 查看获取:完整插件模式、VueUse集成、TypeScript类型定义、常见模式(持久化、路由、日志)
references/plugins-composables.mdUsing Stores Outside Components
在组件外部使用仓库
The Problem
问题
Stores need the Pinia instance, which is auto-injected in components but not available in module scope.
仓库需要Pinia实例,在组件中会自动注入,但在模块作用域中不可用。
❌ Wrong: Accessing Store at Module Level
❌ 错误方式:在模块级别访问仓库
typescript
// router.ts
import { useUserStore } from '@/stores/user'
// ❌ Fails: Pinia not installed yet
const userStore = useUserStore()
router.beforeEach((to) => {
if (userStore.isLoggedIn) { /* ... */ }
})typescript
// router.ts
import { useUserStore } from '@/stores/user'
// ❌ 失败:Pinia尚未安装
const userStore = useUserStore()
router.beforeEach((to) => {
if (userStore.isLoggedIn) { /* ... */ }
})✅ Right: Accessing Store Inside Callbacks
✅ 正确方式:在回调函数内部访问仓库
typescript
// router.ts
import { useUserStore } from '@/stores/user'
router.beforeEach((to) => {
// ✅ Works: Called after Pinia is installed
const userStore = useUserStore()
if (userStore.isLoggedIn) { /* ... */ }
})Why it works: Router guards execute AFTER completes.
app.use(pinia)typescript
// router.ts
import { useUserStore } from '@/stores/user'
router.beforeEach((to) => {
// ✅ 有效:Pinia安装完成后才会调用
const userStore = useUserStore()
if (userStore.isLoggedIn) { /* ... */ }
})为什么有效:路由守卫在完成后才会执行。
app.use(pinia)SSR: Explicit Pinia Instance
SSR:显式传入Pinia实例
typescript
// server-side
export function setupRouter(pinia) {
router.beforeEach((to) => {
const userStore = useUserStore(pinia) // Pass explicitly
})
}typescript
// 服务端
export function setupRouter(pinia) {
router.beforeEach((to) => {
const userStore = useUserStore(pinia) // 显式传入
})
}Server-Side Rendering & Nuxt
服务端渲染(SSR)与Nuxt
Load for complete SSR and Nuxt integration guide.
references/ssr-and-nuxt.md查看获取完整的SSR和Nuxt集成指南。
references/ssr-and-nuxt.mdSSR Quick Reference
SSR快速参考
State Hydration:
- Server: Serialize with (not
devalue())JSON.stringify - Client: Hydrate BEFORE calling
useStore() - Critical: Call all BEFORE
useStore()in actionsawait
状态水合:
- 服务端:使用序列化(不要用
devalue())JSON.stringify - 客户端:在调用之前完成水合
useStore() - 关键:在actions中的之前调用所有
awaituseStore()
Nuxt 3/4 Integration
Nuxt 3/4集成
bash
bunx nuxi@latest module add piniaAuto-imports: , , , , all stores
defineStorestoreToRefsusePiniaacceptHMRUpdate→ Load for: Complete SSR patterns, Nuxt configuration, server-side data fetching, SSR pitfalls, debugging
references/ssr-and-nuxt.mdbash
bunx nuxi@latest module add pinia自动导入:、、、以及所有仓库
defineStorestoreToRefsusePiniaacceptHMRUpdate→ 查看获取:完整SSR模式、Nuxt配置、服务端数据获取、SSR陷阱、调试方法
references/ssr-and-nuxt.mdTesting
测试
Load for complete testing guide.
references/testing-guide.md查看获取完整测试指南。
references/testing-guide.mdTesting Quick Start
测试快速开始
typescript
import { setActivePinia, createPinia } from 'pinia'
beforeEach(() => {
setActivePinia(createPinia()) // Fresh Pinia for each test
})typescript
import { setActivePinia, createPinia } from 'pinia'
beforeEach(() => {
setActivePinia(createPinia()) // 每个测试使用全新的Pinia
})Component Testing
组件测试
bash
bun add -d @pinia/testingtypescript
import { createTestingPinia } from '@pinia/testing'
mount(Component, {
global: { plugins: [createTestingPinia()] }
})→ Load for: Complete test patterns, stubbing actions, mocking getters, async testing, SSR testing
references/testing-guide.mdbash
bun add -d @pinia/testingtypescript
import { createTestingPinia } from '@pinia/testing'
mount(Component, {
global: { plugins: [createTestingPinia()] }
})→ 查看获取:完整测试模式、Stub Actions、Mock Getters、异步测试、SSR测试
references/testing-guide.mdHot Module Replacement (HMR)
热模块替换(HMR)
Vite Setup
Vite配置
typescript
// stores/counter.ts
import { defineStore, acceptHMRUpdate } from 'pinia'
export const useCounterStore = defineStore('counter', {
// store definition
})
if (import.meta.hot) {
import.meta.hot.accept(acceptHMRUpdate(useCounterStore, import.meta.hot))
}typescript
// stores/counter.ts
import { defineStore, acceptHMRUpdate } from 'pinia'
export const useCounterStore = defineStore('counter', {
// 仓库定义
})
if (import.meta.hot) {
import.meta.hot.accept(acceptHMRUpdate(useCounterStore, import.meta.hot))
}Webpack Setup
Webpack配置
typescript
if (import.meta.webpackHot) {
import.meta.webpackHot.accept(acceptHMRUpdate(useCounterStore, import.meta.webpackHot))
}Benefits:
- Edit stores without full page reload
- Preserve application state during development
- Faster development iteration
typescript
if (import.meta.webpackHot) {
import.meta.webpackHot.accept(acceptHMRUpdate(useCounterStore, import.meta.webpackHot))
}优势:
- 修改仓库无需刷新整个页面
- 开发过程中保留应用状态
- 加快开发迭代速度
Options API Usage
Options API用法
For projects still using Options API, load complete mapper documentation.
→ Load for: Complete Options API integration, all mappers (, , , )
references/state-getters-actions.mdmapStoresmapStatemapWritableStatemapActions对于仍在使用Options API的项目,请查看完整的映射器文档。
→ 查看获取:完整Options API集成、所有映射器(、、、)
references/state-getters-actions.mdmapStoresmapStatemapWritableStatemapActionsMigrating from Vuex
从Vuex迁移
Load for complete migration guide.
references/vuex-migration.md查看获取完整迁移指南。
references/vuex-migration.mdQuick Conversion Overview
快速转换概述
Key Changes:
- Remove (automatic via store ID)
namespaced - Eliminate (direct state mutation)
mutations - Replace with direct mutations
commit() - Replace /
rootStatewith store importsrootGetters - Use instead of custom clear mutations
store.$reset()
Directory: → (each module = separate store)
store/modules/stores/→ Load for: Complete conversion steps, component migration, checklist, gradual migration strategy
references/vuex-migration.md主要变化:
- 移除(通过仓库ID自动实现)
namespaced - 取消(直接修改state)
mutations - 用直接修改替代
commit() - 用仓库导入替代/
rootStaterootGetters - 使用替代自定义的清空mutations
store.$reset()
目录结构: → (每个模块对应一个独立仓库)
store/modules/stores/→ 查看获取:完整转换步骤、组件迁移、检查清单、渐进式迁移策略
references/vuex-migration.mdCritical Rules
重要规则
Always Do
必须遵守
✅ Define all state properties in or return them from setup stores
✅ Use when destructuring state/getters in components
✅ Call BEFORE mounting the app
✅ Return all state from setup stores (private state breaks SSR/DevTools)
✅ Call inside functions/callbacks when used outside components
✅ Use for development HMR support
✅ Type return values when getters use to access other getters
✅ Use for SSR state serialization (prevents XSS)
✅ Hydrate state BEFORE calling any on the client (SSR)
✅ Call all BEFORE any in async actions (SSR)
state()storeToRefs()app.use(pinia)useStore()acceptHMRUpdate()thisdevalueuseStore()useStore()await✅ 在中定义所有state属性,或在Setup仓库中返回它们
✅ 在组件中解构state/getters时使用
✅ 在挂载应用前调用
✅ Setup仓库返回所有state属性(私有state会破坏SSR/DevTools)
✅ 在组件外部使用时,在函数/回调内部调用
✅ 为开发环境添加以支持HMR
✅ 当getters使用访问其他getters时,指定返回值类型
✅ 使用进行SSR状态序列化(防止XSS)
✅ 在客户端(SSR场景)调用任何之前完成状态水合
✅ 在异步actions中的之前调用所有
state()storeToRefs()app.use(pinia)useStore()acceptHMRUpdate()thisdevalueuseStore()awaituseStore()Never Do
禁止操作
❌ Add state properties dynamically after store creation
❌ Destructure store directly without (loses reactivity)
❌ Use arrow functions for actions (need context)
❌ Return private state in setup stores (breaks SSR/DevTools/plugins)
❌ Call at module top-level (before Pinia installed)
❌ Create circular dependencies between stores (both reading each other's state)
❌ Use for SSR serialization (vulnerable to XSS)
❌ Call after in actions (breaks SSR)
❌ Forget to type getter return values when using
❌ Skip in unit tests
storeToRefs()thisuseStore()JSON.stringify()useStore()awaitthisbeforeEach(() => setActivePinia(createPinia()))❌ 仓库创建后动态添加state属性
❌ 不使用直接解构仓库(会丢失响应式)
❌ 为actions使用箭头函数(需要上下文)
❌ 在Setup仓库中返回私有state(会破坏SSR/DevTools/插件)
❌ 在模块顶层调用(Pinia安装前)
❌ 在仓库之间创建循环依赖(互相读取对方的state)
❌ 使用进行SSR序列化(易受XSS攻击)
❌ 在actions中的之后调用(会破坏SSR)
❌ 当使用时忘记指定getter的返回值类型
❌ 在单元测试中跳过
storeToRefs()thisuseStore()JSON.stringify()awaituseStore()thisbeforeEach(() => setActivePinia(createPinia()))Known Issues Prevention
已知问题预防
This skill prevents 12 documented issues:
本指南可预防12个已记录的问题:
Issue #1: Lost Reactivity from Direct Destructuring
问题#1:直接解构导致响应式丢失
Error: State changes don't update in template after destructuring
Why It Happens: JavaScript destructuring breaks Vue reactivity
Prevention: Always use for state/getters
storeToRefs()错误:解构后state变化无法更新模板
原因:JavaScript解构会破坏Vue响应式
预防:始终使用处理state/getters
storeToRefs()Issue #2: Cannot Add State Properties Dynamically
问题#2:无法动态添加state属性
Error: New properties added after store creation aren't reactive
Why It Happens: Pinia needs all properties defined upfront for reactivity
Prevention: Declare all properties in , even if initially
state()undefined错误:仓库创建后添加的新属性不具备响应式
原因:Pinia需要提前定义所有属性以实现响应式
预防:在中声明所有属性,即使初始值为
state()undefinedIssue #3: Store Not Found Before Pinia Install
问题#3:Pinia安装前无法找到仓库
Error: returns undefined
Why It Happens: Calling before
Prevention: Call before mounting or accessing stores
getActivePinia()useStore()app.use(pinia)app.use(pinia)错误:返回undefined
原因:在之前调用
预防:在挂载应用或访问仓库前调用
getActivePinia()app.use(pinia)useStore()app.use(pinia)Issue #4: Setup Store Private State Breaks SSR
问题#4:Setup仓库的私有state破坏SSR
Error: State not serialized/hydrated correctly in SSR
Why It Happens: Properties not returned from setup aren't tracked
Prevention: Return ALL state properties from setup stores
错误:SSR中state序列化/水合不正确
原因:未返回的属性不会被追踪
预防:Setup仓库返回所有state属性
Issue #5: Getters with this
Don't Infer Types
this问题#5:使用this
的Getters无法推断类型
thisError: TypeScript can't infer return type when getter uses
Source: Known TypeScript limitation with Pinia
Prevention: Explicitly type return value:
thisgetterName(): ReturnType { ... }错误:TypeScript无法推断使用的getter的返回类型
来源:Pinia的已知TypeScript限制
预防:显式指定返回值类型:
thisgetterName(): ReturnType { ... }Issue #6: Options API Store Suffix Confusion
问题#6:Options API仓库后缀混淆
Error: Can't find in component
Why It Happens: automatically adds 'Store' suffix
Prevention: Use store name + 'Store' or call
this.counterStoremapStores()setMapStoreSuffix()错误:组件中无法找到
原因:会自动添加'Store'后缀
预防:使用仓库名称+'Store',或调用
this.counterStoremapStores()setMapStoreSuffix()Issue #7: Actions Called After await
Break SSR
await问题#7:await
后调用Actions破坏SSR
awaitError: Wrong Pinia instance used in SSR, causing state pollution
Why It Happens: changes execution context in async functions
Prevention: Call all before any statements
awaituseStore()await错误:SSR中使用错误的Pinia实例,导致state污染
原因:会改变异步函数的执行上下文
预防:在所有语句之前调用
awaitawaituseStore()Issue #8: Circular Store Dependencies Crash App
问题#8:仓库循环依赖导致应用崩溃
Error: Maximum call stack exceeded
Why It Happens: Both stores read each other's state during initialization
Prevention: Use getters/actions for cross-store access, not setup-time reads
错误:超出最大调用栈
原因:初始化时两个仓库互相读取对方的state
预防:使用getters/actions进行跨仓库访问,而非初始化时读取
Issue #9: XSS Vulnerability in SSR State Serialization
问题#9:SSR状态序列化存在XSS漏洞
Error: User input in state can execute malicious scripts
Why It Happens: doesn't escape executable code
Prevention: Use library for safe serialization
JSON.stringify()devalue错误:state中的用户输入可能执行恶意脚本
原因:不会转义可执行代码
预防:使用库进行安全序列化
JSON.stringify()devalueIssue #10: HMR Doesn't Work in Development
问题#10:开发环境中HMR无效
Error: Changes to store require full page reload
Why It Happens: Vite/webpack HMR not configured for store
Prevention: Add block to each store file
acceptHMRUpdate()错误:修改仓库需要刷新整个页面
原因:Vite/webpack未为仓库配置HMR
预防:为每个仓库文件添加代码块
acceptHMRUpdate()Issue #11: Composables Return Functions Break Option Stores
问题#11:组合式函数返回的函数破坏Option仓库
Error: Store state contains non-serializable functions
Why It Happens: Option stores can only return writable refs
Prevention: Use setup stores for complex composables, or extract only writable state
state()错误:仓库state包含不可序列化的函数
原因:Option仓库的只能返回可写的refs
预防:使用Setup仓库处理复杂组合式函数,或仅提取可写state
state()Issue #12: State Not Reset Between Unit Tests
问题#12:单元测试之间state未重置
Error: Tests affect each other, sporadic failures
Why It Happens: Single Pinia instance shared across tests
Prevention: in test suites
beforeEach(() => setActivePinia(createPinia()))错误:测试互相影响,出现偶发失败
原因:多个测试共享同一个Pinia实例
预防:在测试套件中添加
beforeEach(() => setActivePinia(createPinia()))Package Versions (Verified 2025-11-21)
包版本(2025-11-21验证)
Core: ,
Nuxt: ,
Testing: ,
SSR: (for safe serialization)
pinia@^3.0.4vue@^3.5.24@pinia/nuxt@^0.11.2nuxt@^3.13.0@pinia/testing@^1.0.2vitest@^1.0.0devalue@^5.3.2核心:,
Nuxt:,
测试:,
SSR:(用于安全序列化)
pinia@^3.0.4vue@^3.5.24@pinia/nuxt@^0.11.2nuxt@^3.13.0@pinia/testing@^1.0.2vitest@^1.0.0devalue@^5.3.2Common Patterns
常见模式
See reference files for complete pattern examples:
- Authentication stores →
references/state-getters-actions.md - Persistence plugins →
references/plugins-composables.md - Form stores → (setup store examples)
references/store-syntax-guide.md - Router integration → (accessing stores outside components)
references/state-getters-actions.md
查看参考文件获取完整模式示例:
- 认证仓库 →
references/state-getters-actions.md - 持久化插件 →
references/plugins-composables.md - 表单仓库 → (Setup仓库示例)
references/store-syntax-guide.md - 路由集成 → (在组件外部访问仓库)
references/state-getters-actions.md
Official Documentation
官方文档
- Pinia: https://pinia.vuejs.org/
- Getting Started: https://pinia.vuejs.org/getting-started.html
- Core Concepts: https://pinia.vuejs.org/core-concepts/
- SSR Guide: https://pinia.vuejs.org/ssr/
- Nuxt Integration: https://pinia.vuejs.org/ssr/nuxt.html
- Testing: https://pinia.vuejs.org/cookbook/testing.html
- Vuex Migration: https://pinia.vuejs.org/cookbook/migration-vuex.html
- GitHub: https://github.com/vuejs/pinia
- Pinia:https://pinia.vuejs.org/
- 快速开始:https://pinia.vuejs.org/getting-started.html
- 核心概念:https://pinia.vuejs.org/core-concepts/
- SSR指南:https://pinia.vuejs.org/ssr/
- Nuxt集成:https://pinia.vuejs.org/ssr/nuxt.html
- 测试:https://pinia.vuejs.org/cookbook/testing.html
- Vuex迁移:https://pinia.vuejs.org/cookbook/migration-vuex.html
- GitHub:https://github.com/vuejs/pinia
Troubleshooting
故障排除
Problem: "getActivePinia() was called with no active Pinia"
问题:"getActivePinia() was called with no active Pinia"
Solution:
- Ensure is called before mounting
app.use(pinia) - If outside component, call inside callback/function
useStore() - For SSR, pass pinia instance explicitly:
useStore(pinia)
解决方案:
- 确保在挂载前调用
app.use(pinia) - 如果在组件外部使用,在回调/函数内部调用
useStore() - SSR场景下,显式传入pinia实例:
useStore(pinia)
Problem: State changes don't update in template
问题:state变化无法更新模板
Solution: Use instead of direct destructuring
storeToRefs()解决方案:使用替代直接解构
storeToRefs()Problem: Getter using this
has TypeScript errors
this问题:使用this
的Getter存在TypeScript错误
thisSolution: Explicitly type the return value:
myGetter(): ReturnType { return this.otherGetter }解决方案:显式指定返回值类型:
myGetter(): ReturnType { return this.otherGetter }Problem: $reset() not available in setup store
问题:Setup仓库中无法使用$reset()
Solution: Implement custom reset manually:
typescript
function $reset() {
count.value = 0
name.value = ''
}
return { count, name, $reset }解决方案:手动实现自定义重置:
typescript
function $reset() {
count.value = 0
name.value = ''
}
return { count, name, $reset }Problem: HMR not working for stores
问题:仓库的HMR无效
Solution: Add HMR acceptance block:
typescript
if (import.meta.hot) {
import.meta.hot.accept(acceptHMRUpdate(useMyStore, import.meta.hot))
}解决方案:添加HMR接收代码块:
typescript
if (import.meta.hot) {
import.meta.hot.accept(acceptHMRUpdate(useMyStore, import.meta.hot))
}Problem: Tests fail intermittently
问题:测试偶发失败
Solution: Create fresh Pinia in :
beforeEach()typescript
beforeEach(() => {
setActivePinia(createPinia())
})解决方案:在中创建全新的Pinia:
beforeEach()typescript
beforeEach(() => {
setActivePinia(createPinia())
})When to Load References
何时查看参考文件
Load when:
references/store-syntax-guide.md- Need detailed comparison between Option and Setup store syntaxes
- Deciding which syntax to use for a new store
- Questions about Option vs Setup stores trade-offs
- Need complete examples of both syntaxes
Load when:
references/state-getters-actions.md- Need complete API reference for state, getters, or actions
- Questions about ,
$patch, or$subscribe$onAction - Implementing store composition patterns
- Using Options API mappers (,
mapStores,mapState)mapActions - Accessing stores outside components (router, plugins)
Load when:
references/plugins-composables.md- Creating custom Pinia plugins
- Integrating VueUse or other composables into stores
- Need persistence, routing, or logging plugin patterns
- Questions about TypeScript typing for plugins
- Advanced composables integration
Load when:
references/ssr-and-nuxt.md- Setting up server-side rendering
- Integrating with Nuxt 3/4
- Questions about state hydration or serialization
- SSR-related errors (wrong Pinia instance, hydration mismatch)
- Nuxt auto-imports or configuration
- Server-side data fetching patterns
Load when:
references/testing-guide.md- Setting up unit tests for stores
- Testing components that use Pinia stores
- Need to stub actions or mock getters
- Questions about
createTestingPinia - Testing SSR stores
- Vitest or testing framework integration
Load when:
references/vuex-migration.md- Migrating existing Vuex codebase to Pinia
- Questions about Vuex→Pinia conversion
- Need migration checklist or examples
- Gradual migration strategy needed
当以下情况时查看:
references/store-syntax-guide.md- 需要Option和Setup仓库语法的详细对比
- 为新仓库选择语法
- 对Option和Setup仓库的权衡有疑问
- 需要两种语法的完整示例
当以下情况时查看:
references/state-getters-actions.md- 需要state、getters或actions的完整API参考
- 对、
$patch或$subscribe有疑问$onAction - 实现仓库组合模式
- 使用Options API映射器(、
mapStores、mapState)mapActions - 在组件外部访问仓库(路由、插件)
当以下情况时查看:
references/plugins-composables.md- 创建自定义Pinia插件
- 将VueUse或其他组合式函数集成到仓库
- 需要持久化、路由或日志插件模式
- 对插件的TypeScript类型定义有疑问
- 高级组合式函数集成
当以下情况时查看:
references/ssr-and-nuxt.md- 配置服务端渲染
- 与Nuxt 3/4集成
- 对state水合或序列化有疑问
- 遇到SSR相关错误(Pinia实例错误、水合不匹配)
- Nuxt自动导入或配置
- 服务端数据获取模式
当以下情况时查看:
references/testing-guide.md- 配置仓库的单元测试
- 测试使用Pinia仓库的组件
- 需要Stub Actions或Mock Getters
- 对有疑问
createTestingPinia - 测试SSR仓库
- Vitest或测试框架集成
当以下情况时查看:
references/vuex-migration.md- 将现有Vuex代码库迁移到Pinia
- 对Vuex→Pinia的转换有疑问
- 需要迁移检查清单或示例
- 需要渐进式迁移策略
Complete Setup Checklist
完整配置检查清单
- Installed package
pinia - Created Pinia instance with
createPinia() - Registered with before mounting
app.use(pinia) - Created stores directory (e.g., )
src/stores/ - Defined at least one store with
defineStore() - Used when destructuring in components
storeToRefs() - Typed getter return values when using
this - Added HMR support with (development)
acceptHMRUpdate() - Configured SSR hydration (if using SSR)
- Configured (if using Nuxt)
@pinia/nuxt - Set up testing with (if testing)
createTestingPinia() - All stores follow consistent naming:
use[Name]Store - Verified DevTools integration works
Questions? Issues?
- Check official docs: https://pinia.vuejs.org/
- Review "Known Issues Prevention" section above
- Verify setup checklist is complete
- Check for TypeScript configuration issues
- Ensure Pinia is installed before using stores
- 已安装包
pinia - 使用创建Pinia实例
createPinia() - 在挂载前通过注册
app.use(pinia) - 创建了stores目录(例如)
src/stores/ - 使用定义至少一个仓库
defineStore() - 在组件中解构时使用
storeToRefs() - 当使用时为getter指定返回值类型
this - 添加了以支持开发环境HMR
acceptHMRUpdate() - 配置了SSR状态水合(如果使用SSR)
- 配置了(如果使用Nuxt)
@pinia/nuxt - 使用配置测试(如果需要测试)
createTestingPinia() - 所有仓库遵循统一命名:
use[Name]Store - 验证DevTools集成正常工作
有疑问?遇到问题?
- 查看官方文档:https://pinia.vuejs.org/
- 回顾上方的「已知问题预防」部分
- 验证配置检查清单已完成
- 检查TypeScript配置问题
- 确保在使用仓库前已安装Pinia