Pinia 安装与配置 #

安装 Pinia #

使用 npm #

bash
npm install pinia

使用 yarn #

bash
yarn add pinia

使用 pnpm #

bash
pnpm add pinia

Vue 3 项目配置 #

基础配置 #

在 Vue 3 项目中,需要在 main.ts 中创建并注册 Pinia:

ts
// main.ts
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'

const app = createApp(App)

// 创建 Pinia 实例
const pinia = createPinia()

// 注册 Pinia
app.use(pinia)

app.mount('#app')

使用 TypeScript #

Pinia 天然支持 TypeScript,无需额外配置:

ts
// 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')

配合 Vue Router #

ts
// main.ts
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import { createRouter, createWebHistory } from 'vue-router'
import App from './App.vue'
import routes from './routes'

const app = createApp(App)

const pinia = createPinia()
const router = createRouter({
  history: createWebHistory(),
  routes
})

app.use(pinia)
app.use(router)

app.mount('#app')

Vue 2 项目配置 #

如果你需要在 Vue 2 项目中使用 Pinia,需要安装额外的兼容包:

安装 #

bash
npm install pinia @vue/composition-api

配置 #

ts
// main.ts
import Vue from 'vue'
import { createPinia, PiniaVuePlugin } from 'pinia'
import App from './App.vue'

// 安装 Pinia 插件
Vue.use(PiniaVuePlugin)

// 创建 Pinia 实例
const pinia = createPinia()

new Vue({
  pinia,
  render: h => h(App)
}).$mount('#app')

Nuxt.js 项目配置 #

Nuxt 3 #

在 Nuxt 3 中,Pinia 已经内置支持:

ts
// nuxt.config.ts
export default defineNuxtConfig({
  modules: [
    '@pinia/nuxt'
  ]
})

Nuxt 2 #

对于 Nuxt 2,需要使用 @pinia/nuxt 模块:

bash
npm install @pinia/nuxt pinia
js
// nuxt.config.js
export default {
  modules: [
    '@pinia/nuxt'
  ]
}

创建第一个 Store #

安装配置完成后,创建你的第一个 Store:

项目结构 #

text
src/
├── stores/
│   ├── index.ts          # Store 导出
│   └── counter.ts        # 计数器 Store
├── App.vue
└── main.ts

定义 Store #

ts
// stores/counter.ts
import { defineStore } from 'pinia'

export const useCounterStore = defineStore('counter', {
  state: () => ({
    count: 0
  }),
  getters: {
    doubleCount: (state) => state.count * 2
  },
  actions: {
    increment() {
      this.count++
    },
    decrement() {
      this.count--
    }
  }
})

在组件中使用 #

vue
<template>
  <div>
    <h2>计数器</h2>
    <p>当前值: {{ counter.count }}</p>
    <p>两倍值: {{ counter.doubleCount }}</p>
    <button @click="counter.increment">+1</button>
    <button @click="counter.decrement">-1</button>
  </div>
</template>

<script setup>
import { useCounterStore } from '@/stores/counter'

const counter = useCounterStore()
</script>

开发工具配置 #

Vue DevTools #

Pinia 完整支持 Vue DevTools,可以:

  • 查看所有 Store 的状态
  • 实时修改状态
  • 查看状态变更历史
  • 时间旅行调试

确保安装了最新版本的 Vue DevTools:

开发模式提示 #

Pinia 在开发模式下会提供有用的警告和提示:

ts
// 在开发模式下,Pinia 会警告以下问题:
// 1. 在组件外使用 Store
// 2. 直接解构 state(会失去响应性)
// 3. 未正确初始化 Pinia

常见问题 #

1. “getActivePinia was called with no active Pinia” 错误 #

这个错误表示在 Pinia 初始化之前就使用了 Store:

ts
// 错误示例
import { useCounterStore } from './stores/counter'

const store = useCounterStore() // 错误!Pinia 还未初始化

// 正确示例:在组件或函数内部使用
function someFunction() {
  const store = useCounterStore() // 正确
}

2. Store 之间相互引用 #

Store 可以相互引用,但要注意初始化顺序:

ts
// stores/user.ts
export const useUserStore = defineStore('user', {
  state: () => ({ name: 'John' })
})

// stores/cart.ts
export const useCartStore = defineStore('cart', {
  state: () => ({ items: [] }),
  actions: {
    checkout() {
      const userStore = useUserStore() // 在 action 内部引用
      console.log(`Checking out for ${userStore.name}`)
    }
  }
})

3. SSR 配置 #

对于服务端渲染(SSR)项目,需要确保每个请求创建新的 Pinia 实例:

ts
// 服务端
import { createPinia } from 'pinia'

// 每个请求创建新实例
const pinia = createPinia()
const app = createApp(App)
app.use(pinia)

下一步 #

现在你已经完成了 Pinia 的安装和配置,接下来让我们深入了解 Pinia 的核心概念。

最后更新:2026-03-28