Vue3 Pinia状态管理安装配置与Store代码示例
Pinia是Vue官方推荐的状态管理库,原文说明它始于2019年的一次实验,目标是提供带组合式API的Vue状态管理方案;目前同时支持Vue 2和Vue 3,且不强制使用组合式API。它主要用于跨组件、跨页面共享状态,并提供Devtools、热更新、时间旅行调试、TypeScript自动补全和服务端渲染支持。与Vuex相比,Pinia最明显的变化是取消mutations:修改状态不再必须commit,action可以直接改state,同步和异步逻辑都放在action中,原文给出的代码量减少幅度为30%到50%。下面按安装挂载、Store定义、组件调用、Vuex对比和选型迁移来整理。一、安装与挂载
安装命令:
npm install pinia
# 或
yarn add pinia
# 或
pnpm add pinia
创建实例并挂载到Vue应用:
// src/store/index.js
import { createPinia } from 'pinia'
const pinia = createPinia()
export default pinia
// src/main.js
import { createApp } from 'vue'
import App from './App.vue'
import pinia from './store'
const app = createApp(App)
app.use(pinia)
app.mount('#app')
这里的关键是createPinia()生成实例,再通过app.use(pinia)安装;后续组件里使用的Store都依赖这个挂载过程。
二、Option Store写法
Option Store接近Vue选项式API,适合从Vuex迁移的开发者。state返回数据对象,getters基于state派生并带缓存,actions放同步或异步方法。示例:
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0,
name: 'Pinia'
}),
getters: {
doubleCount: (state) => state.count * 2,
message: (state) => `${state.name} says count is ${state.count}`
},
actions: {
increment() {
this.count++
},
decrement() {
this.count--
},
async fetchCount() {
const res = await fetch('/api/count')
this.count = await res.json()
}
}
})
组件中用useCounterStore()实例化,再直接访问state、getters和actions:
<template>
<div>
<p>Count: {{ counter.count }}</p>
<p>Double: {{ counter.doubleCount }}</p>
<p>{{ counter.message }}</p>
<button @click='counter.increment'>+</button>
<button @click='counter.decrement'>-</button>
<button @click='counter.fetchCount'>获取远程数据</button>
</div>
</template>
<script setup>
import { useCounterStore } from '@/store/counter'
const counter = useCounterStore()
</script>
三、Setup Store写法
Setup Store直接使用ref、computed和普通函数,适合习惯Composition API的开发者。原文明确:ref()对应state,computed()对应getters,function()对应actions;必须返回所有state属性,否则会影响SSR和Devtools。示例:
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
export const useCounterStore = defineStore('counter', () => {
const count = ref(0)
const name = ref('Pinia')
const doubleCount = computed(() => count.value * 2)
const message = computed(() => `${name.value} says count is ${count.value}`)
function increment() {
count.value++
}
function decrement() {
count.value--
}
async function fetchCount() {
const res = await fetch('/api/count')
count.value = await res.json()
}
return { count, name, doubleCount, message, increment, decrement, fetchCount }
})
组件调用方式与Option Store一致,仍然先useCounterStore(),再访问counter.count、counter.increment等。区别主要在Store定义侧:Setup Store更灵活,但返回列表要完整。
四、选项式API组件中的映射
如果Vue 3项目仍使用选项式API,可以用mapState、mapActions映射:
<script>
import { mapState, mapActions } from 'pinia'
import { useCounterStore } from '@/store/counter'
export default {
computed: {
...mapState(useCounterStore, ['count', 'doubleCount'])
},
methods: {
...mapActions(useCounterStore, ['increment', 'decrement'])
}
}
</script>
这样组件内可以按原有选项式API方式使用state、getters和actions,不必全部改成script setup。
五、与Vuex的核心差异
原文的对比可以归纳为几个关键点:Vuex 4修改状态必须通过commit mutation,Pinia取消mutation,直接在action中修改;Vuex采用单一Store树并通过modules划分,Pinia是多Store设计,每个Store独立存在,通过import引用;TypeScript方面,Vuex需要大量手动类型声明,Pinia自动类型推导;模块化方面,Vuex依赖namespaced: true和嵌套路径,Pinia天然模块化;样板代码Vuex更多,Pinia更简洁,原文给出的减少幅度是30%到50%;学习曲线上Vuex较陡,Pinia接近Vue组件写法;热更新Pinia更友好。
Vuex 4的典型写法:
const store = new Vuex.Store({
state: { count: 0 },
mutations: {
increment(state) { state.count++ }
},
actions: {
incrementAsync({ commit }) {
setTimeout(() => commit('increment'), 1000)
}
},
getters: {
doubleCount: state => state.count * 2
}
})
// 组件中
this.$store.commit('increment')
this.$store.dispatch('incrementAsync')
Pinia对应写法:
export const useCounterStore = defineStore('counter', {
state: () => ({ count: 0 }),
actions: {
increment() { this.count++ },
async incrementAsync() {
await delay(1000)
this.count++
}
},
getters: {
doubleCount: state => state.count * 2
}
})
// 组件中
counter.increment()
counter.incrementAsync()
优缺点方面,原文认为Pinia语法简洁、无需mutations、样板代码少、TypeScript类型推导开箱即用、多Store天然模块化、轻量且热更新体验更好;不足是社区生态相对较新,插件不如Vuex丰富,学习资料也相对少。Vuex的优点是社区成熟、插件和工具丰富、学习资料多、严格单向数据流在大型项目里更可控;缺点是语法复杂、样板代码多、TypeScript支持不够友好,需要大量手动声明。
六、选型与迁移建议
新Vue 3项目优先选Pinia,原文给出的理由是Vue官方推荐、更现代、更简洁。Vue 2项目升级可以逐步迁移,也可以直接使用Pinia,因为Pinia同时支持Vue 2。大型遗留项目如果已经深度使用Vuex,建议渐进式迁移,允许Vuex与Pinia共存;原文提到的做法是新功能用Pinia,旧模块逐步迁移,并创建一个“桥接Store”,把Vuex中频繁使用的核心状态优先迁移到Pinia。中小型项目不一定需要状态管理库,ref/reactive配合provide/inject可能已经足够。
总结:Pinia的核心改动是取消mutations、让action直接修改状态并处理异步,同时用多Store和TypeScript推导降低样板代码;Option Store、Setup Store和选项式API映射三种用法覆盖了不同组件风格。对Vue 3新项目,按原文结论应优先考虑Pinia;对Vuex存量项目,则按渐进迁移和共存的思路处理更稳妥。
Re: Vue3 Pinia状态管理安装配置与Store代码示例
整理得很清楚,安装挂载、Option Store、Setup Store 三块基本能直接拿去用,代码示例也很完整。 补充几点在实际项目里比较常遇到的问题: 1. 结构化解构要保持响应性。直接 `const { count } = useCounterStore()` 会丢响应,需要用 `storeToRefs(store)` 取 state 和 getters,action 直接从 store 上拿就行。 2. `$reset()` 只有 Option Store 自带,Setup Store 得自己写一个重置函数,把各个 ref 重新赋值,这点从 Option 切到 Setup 时容易踩。 3. 批量改 state 用 `$patch`,传对象或者传函数都可以,后者在改数组、做条件判断时更灵活。 4. 持久化 Pinia 本身不带,常见做法是加一个插件或自己订阅 store 写 localStorage,注意 SSR 环境下别直接访问 window。 另外你这篇好像没写完,末尾停在 `mapActi` 那里,选项式 API 的 mapState、mapActions 映射示例和后面的 Vuex 对比、选型迁移都还没出来,方便的话补一下?尤其是迁移那块,从 Vuex 的 mutations 挪到 action 里,团队里老代码怎么平滑过渡,应该不少人关心。Re: Vue3 Pinia状态管理安装配置与Store代码示例
整理得很系统,安装挂载部分把 createPinia() 和 app.use(pinia) 的关系讲清楚了,后面 Option Store 和 Setup Store 两套示例对照起来也很直观。尤其点明 Setup Store 里 ref 对应 state、computed 对应 getters、function 对应 actions,并且必须返回所有 state 属性,这个提醒对 SSR 和 Devtools 很关键。取消 mutations、action 直接改 state 的说明也简洁,和 Vuex 的差异一眼能看出来。就是选项式 API 映射部分好像没发完,停在 mapState、mapActi 那里,期待后面补上 mapActions 的完整示例。整体作为入门配置和迁移参考挺实用的。Re: Vue3 Pinia状态管理安装配置与Store代码示例
这篇整理得很系统,安装挂载、Option Store、Setup Store 和组件调用顺序都讲清楚了,代码示例也直接能对照着用。对从 Vuex 迁移的人来说,Option Store 的写法会比较亲切;习惯组合式 API 的话,Setup Store 里 ref 对应 state、computed 对应 getters、function 对应 actions 的对应关系总结得很直观。特别提醒 Setup Store 必须返回所有 state 属性这一点很关键,容易在 SSR 和 Devtools 上踩坑。 另外首帖最后选项式 API 映射部分好像还没贴完,期待后续能把 mapState、mapActions 的完整用法补上,最好再带一个组件里怎么映射 getters 的小例子,这样整篇从安装到组件使用就更完整了。整体内容对实际项目配置挺有帮助。
页:
[1]