pinia-v3

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Pinia 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 pinia
bash
bun add pinia

or

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 debugging
bun 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
    app.use(pinia)
    before mounting the app
  • 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
references/store-syntax-guide.md
for complete comparison of Option vs Setup stores.
查看
references/store-syntax-guide.md
获取Option和Setup仓库的完整对比。

Quick Overview

快速概述

Pinia supports two store definition syntaxes:
Option Stores:
  • Similar to Vue Options API
  • Built-in
    $reset()
    method
  • 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
references/store-syntax-guide.md
for:
Complete syntax comparison, examples, choosing criteria

Pinia支持两种仓库定义语法:
Option仓库
  • 类似Vue Options API
  • 内置
    $reset()
    方法
  • 最适用:简单场景、熟悉Vuex的团队
Setup仓库
  • 使用Composition API模式
  • 支持完整的组合式函数集成
  • 最适用:高级模式、需要观察者/VueUse集成的场景
→ 查看
references/store-syntax-guide.md
获取
:完整语法对比、示例、选择标准

State, Getters, and Actions

State、Getters和Actions

Load
references/state-getters-actions.md
for complete API reference.
查看
references/state-getters-actions.md
获取完整API参考。

Quick Reference

快速参考

State:
  • Define in
    state: () => ({...})
    (option) or
    ref()
    (setup)
  • Access directly:
    store.count
  • Mutate directly:
    store.count++
    or
    store.$patch({...})
  • Reset:
    store.$reset()
    (option stores only)
Getters:
  • Computed properties:
    getters: { double: (state) => state.count * 2 }
  • Access other getters with
    this
    (must type return value)
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
references/state-getters-actions.md
for:
Complete API, subscriptions, store composition patterns, Options API usage

State
  • state: () => ({...})
    (Option语法)或
    ref()
    (Setup语法)中定义
  • 直接访问:
    store.count
  • 直接修改:
    store.count++
    store.$patch({...})
  • 重置:
    store.$reset()
    (仅Option仓库支持)
Getters
  • 计算属性:
    getters: { double: (state) => state.count * 2 }
  • 使用
    this
    访问其他getters(必须指定返回值类型)
Actions
  • 业务逻辑:
    actions: { increment() { this.count++ } }
  • 支持异步
  • 可直接访问其他仓库
仓库解构
typescript
import { storeToRefs } from 'pinia'

// ✅ 保持响应式
const { name, count } = storeToRefs(store)

// ✅ Actions可直接解构
const { increment } = store
→ 查看
references/state-getters-actions.md
获取
:完整API、订阅、仓库组合模式、Options API用法

Plugins and Composables

插件与组合式函数

Load
references/plugins-composables.md
for complete plugin and composables guide.
查看
references/plugins-composables.md
获取完整的插件和组合式函数指南。

Plugin 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
useLocalStorage
style in
state()
Setup Stores: Full VueUse/composables support
→ Load
references/plugins-composables.md
for:
Complete plugin patterns, VueUse integration, TypeScript typing, common patterns (persistence, router, logger)

Option仓库:仅支持在
state()
中使用
useLocalStorage
这类组合式函数 Setup仓库:完全支持VueUse/组合式函数
→ 查看
references/plugins-composables.md
获取
:完整插件模式、VueUse集成、TypeScript类型定义、常见模式(持久化、路由、日志)

Using 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
app.use(pinia)
completes.
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
references/ssr-and-nuxt.md
for complete SSR and Nuxt integration guide.
查看
references/ssr-and-nuxt.md
获取完整的SSR和Nuxt集成指南。

SSR Quick Reference

SSR快速参考

State Hydration:
  • Server: Serialize with
    devalue()
    (not
    JSON.stringify
    )
  • Client: Hydrate BEFORE calling
    useStore()
  • Critical: Call all
    useStore()
    BEFORE
    await
    in actions
状态水合
  • 服务端:使用
    devalue()
    序列化(不要用
    JSON.stringify
  • 客户端:在调用
    useStore()
    之前完成水合
  • 关键:在actions中的
    await
    之前调用所有
    useStore()

Nuxt 3/4 Integration

Nuxt 3/4集成

bash
bunx nuxi@latest module add pinia
Auto-imports:
defineStore
,
storeToRefs
,
usePinia
,
acceptHMRUpdate
, all stores
→ Load
references/ssr-and-nuxt.md
for:
Complete SSR patterns, Nuxt configuration, server-side data fetching, SSR pitfalls, debugging

bash
bunx nuxi@latest module add pinia
自动导入
defineStore
storeToRefs
usePinia
acceptHMRUpdate
以及所有仓库
→ 查看
references/ssr-and-nuxt.md
获取
:完整SSR模式、Nuxt配置、服务端数据获取、SSR陷阱、调试方法

Testing

测试

Load
references/testing-guide.md
for complete testing guide.
查看
references/testing-guide.md
获取完整测试指南。

Testing 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/testing
typescript
import { createTestingPinia } from '@pinia/testing'

mount(Component, {
  global: { plugins: [createTestingPinia()] }
})
→ Load
references/testing-guide.md
for:
Complete test patterns, stubbing actions, mocking getters, async testing, SSR testing

bash
bun add -d @pinia/testing
typescript
import { createTestingPinia } from '@pinia/testing'

mount(Component, {
  global: { plugins: [createTestingPinia()] }
})
→ 查看
references/testing-guide.md
获取
:完整测试模式、Stub Actions、Mock Getters、异步测试、SSR测试

Hot 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
references/state-getters-actions.md
for:
Complete Options API integration, all mappers (
mapStores
,
mapState
,
mapWritableState
,
mapActions
)

对于仍在使用Options API的项目,请查看完整的映射器文档。
→ 查看
references/state-getters-actions.md
获取
:完整Options API集成、所有映射器(
mapStores
mapState
mapWritableState
mapActions

Migrating from Vuex

从Vuex迁移

Load
references/vuex-migration.md
for complete migration guide.
查看
references/vuex-migration.md
获取完整迁移指南。

Quick Conversion Overview

快速转换概述

Key Changes:
  1. Remove
    namespaced
    (automatic via store ID)
  2. Eliminate
    mutations
    (direct state mutation)
  3. Replace
    commit()
    with direct mutations
  4. Replace
    rootState
    /
    rootGetters
    with store imports
  5. Use
    store.$reset()
    instead of custom clear mutations
Directory:
store/modules/
stores/
(each module = separate store)
→ Load
references/vuex-migration.md
for:
Complete conversion steps, component migration, checklist, gradual migration strategy

主要变化
  1. 移除
    namespaced
    (通过仓库ID自动实现)
  2. 取消
    mutations
    (直接修改state)
  3. 用直接修改替代
    commit()
  4. 用仓库导入替代
    rootState
    /
    rootGetters
  5. 使用
    store.$reset()
    替代自定义的清空mutations
目录结构
store/modules/
stores/
(每个模块对应一个独立仓库)
→ 查看
references/vuex-migration.md
获取
:完整转换步骤、组件迁移、检查清单、渐进式迁移策略

Critical Rules

重要规则

Always Do

必须遵守

✅ Define all state properties in
state()
or return them from setup stores ✅ Use
storeToRefs()
when destructuring state/getters in components ✅ Call
app.use(pinia)
BEFORE mounting the app ✅ Return all state from setup stores (private state breaks SSR/DevTools) ✅ Call
useStore()
inside functions/callbacks when used outside components ✅ Use
acceptHMRUpdate()
for development HMR support ✅ Type return values when getters use
this
to access other getters ✅ Use
devalue
for SSR state serialization (prevents XSS) ✅ Hydrate state BEFORE calling any
useStore()
on the client (SSR) ✅ Call all
useStore()
BEFORE any
await
in async actions (SSR)
✅ 在
state()
中定义所有state属性,或在Setup仓库中返回它们 ✅ 在组件中解构state/getters时使用
storeToRefs()
✅ 在挂载应用前调用
app.use(pinia)
✅ Setup仓库返回所有state属性(私有state会破坏SSR/DevTools) ✅ 在组件外部使用时,在函数/回调内部调用
useStore()
✅ 为开发环境添加
acceptHMRUpdate()
以支持HMR ✅ 当getters使用
this
访问其他getters时,指定返回值类型 ✅ 使用
devalue
进行SSR状态序列化(防止XSS) ✅ 在客户端(SSR场景)调用任何
useStore()
之前完成状态水合 ✅ 在异步actions中的
await
之前调用所有
useStore()

Never Do

禁止操作

❌ Add state properties dynamically after store creation ❌ Destructure store directly without
storeToRefs()
(loses reactivity) ❌ Use arrow functions for actions (need
this
context) ❌ Return private state in setup stores (breaks SSR/DevTools/plugins) ❌ Call
useStore()
at module top-level (before Pinia installed) ❌ Create circular dependencies between stores (both reading each other's state) ❌ Use
JSON.stringify()
for SSR serialization (vulnerable to XSS) ❌ Call
useStore()
after
await
in actions (breaks SSR) ❌ Forget to type getter return values when using
this
❌ Skip
beforeEach(() => setActivePinia(createPinia()))
in unit tests

❌ 仓库创建后动态添加state属性 ❌ 不使用
storeToRefs()
直接解构仓库(会丢失响应式) ❌ 为actions使用箭头函数(需要
this
上下文) ❌ 在Setup仓库中返回私有state(会破坏SSR/DevTools/插件) ❌ 在模块顶层调用
useStore()
(Pinia安装前) ❌ 在仓库之间创建循环依赖(互相读取对方的state) ❌ 使用
JSON.stringify()
进行SSR序列化(易受XSS攻击) ❌ 在actions中的
await
之后调用
useStore()
(会破坏SSR) ❌ 当使用
this
时忘记指定getter的返回值类型 ❌ 在单元测试中跳过
beforeEach(() => 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
storeToRefs()
for state/getters
错误:解构后state变化无法更新模板 原因:JavaScript解构会破坏Vue响应式 预防:始终使用
storeToRefs()
处理state/getters

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
state()
, even if initially
undefined
错误:仓库创建后添加的新属性不具备响应式 原因:Pinia需要提前定义所有属性以实现响应式 预防:在
state()
中声明所有属性,即使初始值为
undefined

Issue #3: Store Not Found Before Pinia Install

问题#3:Pinia安装前无法找到仓库

Error:
getActivePinia()
returns undefined Why It Happens: Calling
useStore()
before
app.use(pinia)
Prevention: Call
app.use(pinia)
before mounting or accessing stores
错误
getActivePinia()
返回undefined 原因:在
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

问题#5:使用
this
的Getters无法推断类型

Error: TypeScript can't infer return type when getter uses
this
Source: Known TypeScript limitation with Pinia Prevention: Explicitly type return value:
getterName(): ReturnType { ... }
错误:TypeScript无法推断使用
this
的getter的返回类型 来源:Pinia的已知TypeScript限制 预防:显式指定返回值类型:
getterName(): ReturnType { ... }

Issue #6: Options API Store Suffix Confusion

问题#6:Options API仓库后缀混淆

Error: Can't find
this.counterStore
in component Why It Happens:
mapStores()
automatically adds 'Store' suffix Prevention: Use store name + 'Store' or call
setMapStoreSuffix()
错误:组件中无法找到
this.counterStore
原因
mapStores()
会自动添加'Store'后缀 预防:使用仓库名称+'Store',或调用
setMapStoreSuffix()

Issue #7: Actions Called After
await
Break SSR

问题#7:
await
后调用Actions破坏SSR

Error: Wrong Pinia instance used in SSR, causing state pollution Why It Happens:
await
changes execution context in async functions Prevention: Call all
useStore()
before any
await
statements
错误:SSR中使用错误的Pinia实例,导致state污染 原因
await
会改变异步函数的执行上下文 预防:在所有
await
语句之前调用
useStore()

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:
JSON.stringify()
doesn't escape executable code Prevention: Use
devalue
library for safe serialization
错误:state中的用户输入可能执行恶意脚本 原因
JSON.stringify()
不会转义可执行代码 预防:使用
devalue
库进行安全序列化

Issue #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
acceptHMRUpdate()
block to each store file
错误:修改仓库需要刷新整个页面 原因: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
state()
can only return writable refs Prevention: Use setup stores for complex composables, or extract only writable state
错误:仓库state包含不可序列化的函数 原因:Option仓库的
state()
只能返回可写的refs 预防:使用Setup仓库处理复杂组合式函数,或仅提取可写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:
beforeEach(() => setActivePinia(createPinia()))
in test suites

错误:测试互相影响,出现偶发失败 原因:多个测试共享同一个Pinia实例 预防:在测试套件中添加
beforeEach(() => setActivePinia(createPinia()))

Package Versions (Verified 2025-11-21)

包版本(2025-11-21验证)

Core:
pinia@^3.0.4
,
vue@^3.5.24
Nuxt:
@pinia/nuxt@^0.11.2
,
nuxt@^3.13.0
Testing:
@pinia/testing@^1.0.2
,
vitest@^1.0.0
SSR:
devalue@^5.3.2
(for safe serialization)

核心
pinia@^3.0.4
,
vue@^3.5.24
Nuxt
@pinia/nuxt@^0.11.2
,
nuxt@^3.13.0
测试
@pinia/testing@^1.0.2
,
vitest@^1.0.0
SSR
devalue@^5.3.2
(用于安全序列化)

Common Patterns

常见模式

See reference files for complete pattern examples:
  • Authentication stores
    references/state-getters-actions.md
  • Persistence plugins
    references/plugins-composables.md
  • Form stores
    references/store-syntax-guide.md
    (setup store examples)
  • Router integration
    references/state-getters-actions.md
    (accessing stores outside components)

查看参考文件获取完整模式示例:
  • 认证仓库
    references/state-getters-actions.md
  • 持久化插件
    references/plugins-composables.md
  • 表单仓库
    references/store-syntax-guide.md
    (Setup仓库示例)
  • 路由集成
    references/state-getters-actions.md
    (在组件外部访问仓库)

Official Documentation

官方文档

Troubleshooting

故障排除

Problem: "getActivePinia() was called with no active Pinia"

问题:"getActivePinia() was called with no active Pinia"

Solution:
  1. Ensure
    app.use(pinia)
    is called before mounting
  2. If outside component, call
    useStore()
    inside callback/function
  3. For SSR, pass pinia instance explicitly:
    useStore(pinia)
解决方案
  1. 确保在挂载前调用
    app.use(pinia)
  2. 如果在组件外部使用,在回调/函数内部调用
    useStore()
  3. SSR场景下,显式传入pinia实例:
    useStore(pinia)

Problem: State changes don't update in template

问题:state变化无法更新模板

Solution: Use
storeToRefs()
instead of direct destructuring
解决方案:使用
storeToRefs()
替代直接解构

Problem: Getter using
this
has TypeScript errors

问题:使用
this
的Getter存在TypeScript错误

Solution: 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())
})

解决方案:在
beforeEach()
中创建全新的Pinia:
typescript
beforeEach(() => {
  setActivePinia(createPinia())
})

When to Load References

何时查看参考文件

Load
references/store-syntax-guide.md
when:
  • 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
references/state-getters-actions.md
when:
  • Need complete API reference for state, getters, or actions
  • Questions about
    $patch
    ,
    $subscribe
    , or
    $onAction
  • Implementing store composition patterns
  • Using Options API mappers (
    mapStores
    ,
    mapState
    ,
    mapActions
    )
  • Accessing stores outside components (router, plugins)
Load
references/plugins-composables.md
when:
  • 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
references/ssr-and-nuxt.md
when:
  • 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
references/testing-guide.md
when:
  • 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
references/vuex-migration.md
when:
  • 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
    pinia
    package
  • Created Pinia instance with
    createPinia()
  • Registered with
    app.use(pinia)
    before mounting
  • Created stores directory (e.g.,
    src/stores/
    )
  • Defined at least one store with
    defineStore()
  • Used
    storeToRefs()
    when destructuring in components
  • Typed getter return values when using
    this
  • Added HMR support with
    acceptHMRUpdate()
    (development)
  • Configured SSR hydration (if using SSR)
  • Configured
    @pinia/nuxt
    (if using Nuxt)
  • Set up testing with
    createTestingPinia()
    (if testing)
  • All stores follow consistent naming:
    use[Name]Store
  • Verified DevTools integration works

Questions? Issues?
  1. Check official docs: https://pinia.vuejs.org/
  2. Review "Known Issues Prevention" section above
  3. Verify setup checklist is complete
  4. Check for TypeScript configuration issues
  5. Ensure Pinia is installed before using stores
  • 已安装
    pinia
  • 使用
    createPinia()
    创建Pinia实例
  • 在挂载前通过
    app.use(pinia)
    注册
  • 创建了stores目录(例如
    src/stores/
  • 使用
    defineStore()
    定义至少一个仓库
  • 在组件中解构时使用
    storeToRefs()
  • 当使用
    this
    时为getter指定返回值类型
  • 添加了
    acceptHMRUpdate()
    以支持开发环境HMR
  • 配置了SSR状态水合(如果使用SSR)
  • 配置了
    @pinia/nuxt
    (如果使用Nuxt)
  • 使用
    createTestingPinia()
    配置测试(如果需要测试)
  • 所有仓库遵循统一命名:
    use[Name]Store
  • 验证DevTools集成正常工作

有疑问?遇到问题?
  1. 查看官方文档:https://pinia.vuejs.org/
  2. 回顾上方的「已知问题预防」部分
  3. 验证配置检查清单已完成
  4. 检查TypeScript配置问题
  5. 确保在使用仓库前已安装Pinia