vuejs/pinia
🍍 Intuitive, type safe, light and flexible Store for Vue using the composition api with DevTools support
vuejs/pinia
🍍 Intuitive, type safe, light and flexible Store for Vue using the composition api with DevTools support
Pinia 是 Vue.js 官方 推荐的状态管理库,由 Vue Router 作者维护,定位为 Vuex 的继任者。它以独立的 Store 为单位组织状态,API 直观、TypeScript 友好,并完整支持 Vue DevTools。当前主分支面向 Vue 3;维护 Vue 2 项目请使用仓库 v2 分支。Pinia 同时提供 Nuxt 模块,可在 SSR 场景下开箱集成。
defineStore 定义 Store,state、getters、actions 结构清晰,心智负担低于传统 Vuex 的 mutations 与 modules 嵌套storeToRefs 等工具在 IDE 中可获得完整类型推导组件间共享用户会话、购物车、主题偏好等状态时,仅靠 props 逐层传递或事件总线很快变得难以维护。Pinia 把全局状态收敛到命名清晰的 Store,组件通过 useXxxStore() 按需订阅,避免「上帝对象」式单例。相比 Vuex,省去 mutations 样板代码,actions 可直接异步请求并修改 state;相比在组件内用 ref/reactive 手写全局单例,Pinia 提供 DevTools、SSR 与 Nuxt 官方集成,更适合中大型 Vue 应用。
setup()、computed 自然协作;跨框架选型时勿强行类比,应按技术栈选择。create-vue 脚手架),或 Nuxt 3 应用。在现有 Vue 3 项目中安装:
npm install pinia使用 pnpm 或 Yarn 时,将 npm install 替换为 pnpm add pinia 或 yarn add pinia。
Nuxt 3 请按官方 SSR 文档配置 @pinia/nuxt 模块,而非仅手动 app.use。
新建项目 可在 npm create vue@latest 向导中勾选 Pinia,脚手架会生成 stores/ 目录与示例 Store。
在应用入口注册 Pinia 插件:
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')创建第一个 Store(建议放在 src/stores/):
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', { state: () => ({ count: 0 }), getters: { double: (state) => state.count * 2, }, actions: { increment() { this.count++ }, },})在组件中使用:
import { useCounterStore } from '@/stores/counter'import { storeToRefs } from 'pinia'
const store = useCounterStore()const { count, double } = storeToRefs(store)也可在 StackBlitz Vue 3 示例 或 Nuxt 3 示例 中在线体验,无需本地安装。
app.use(pinia) 后页面正常渲染。useCounterStore() 并执行 increment(),界面与 count 同步更新。storeToRefs 解构的字段应具备正确类型提示。storeToRefs();actions 可直接从 store 实例解构。defineStore 外,还支持 Setup 函数风格(类似 Composition API);团队应统一一种风格,避免混用增加阅读成本。