现代Vue状态管理:Pinia完全指南
现代Vue状态管理:Pinia完全指南
https://pinia.vuejs.org/logo.svg
为什么选择Pinia?
在Vue生态中,状态管理一直是核心话题。作为Vue官方推荐的状态管理库,Pinia相比Vuex具有显著优势:
✅ 更简单的API - 去掉mutations,只有state/getters/actions
✅ 完美的TypeScript支持 - 自动推断类型,无需额外配置
✅ 模块化设计 - 每个store都是天然模块
✅ Composition API友好 - 完美适配Vue 3的响应式系统
✅ 轻量 - 仅1KB大小,却功能完备
快速入门
安装
npm install pinia
或
yarn add pinia
基本配置
// main.js
import { createApp } from ‘vue’
import { createPinia } from ‘pinia’
import App from ‘./App.vue’
const app = createApp(App)
app.use(createPinia())
app.mount(‘#app’)
核心概念详解
定义Store
// stores/counter.js
import { defineStore } from ‘pinia’
export const useCounterStore = defineStore(‘counter’, {
state: () => ({
count: 0,
user: null
}),
getters: {
doubleCount: (state) => state.count * 2,
},
actions: {
increment() {
this.count++
},
async fetchUser(userId) {
this.user = await api.getUser(userId)
}
}
})
在组件中使用
Count: {{ counter.count }}
Double: {{ counter.doubleCount }}
const pinia = createPinia()
pinia.use(piniaPluginPersistedstate)
插件开发
pinia.use(({ store }) => {
store.KaTeX parse error: Expected 'EOF', got '}' at position 56: …响应store变化 }) }̲) SSR支持 // 服务端 …patch
cartStore.$patch({
items: newItems,
updatedAt: Date.now()
})
批量更新 - 避免重复触发响应
function batchUpdate() {
isBatching.value = true
// 多次状态修改…
nextTick(() => (isBatching.value = false))
}
惰性加载 - 动态注册store
const lazyStore = defineStore(‘lazy’, () => {
// 按需加载的逻辑
})
与Vuex的对比
特性 Pinia Vuex
Vue 3支持 ✅ 需要兼容层
TypeScript 一流支持 需要类型增强
代码组织 更简洁 更冗长
模块热更新 ✅ ❌
包大小 ~1KB ~10KB
最佳实践
命名规范 - 使用useXxxStore的命名约定
逻辑拆分 - 复杂业务逻辑拆分为独立action
避免全局导入 - 只在需要时引入store
类型安全 - 充分利用TypeScript泛型
interface UserState {
name: string
age: number
}
const useUserStore = defineStore<‘user’, UserState>(‘user’, {
// …
})
常见问题解答
Q: 如何在组件外使用store?
// 在路由守卫中
import { useAuthStore } from ‘@/stores/auth’
router.beforeEach((to) => {
const auth = useAuthStore()
if (!auth.isLoggedIn) return ‘/login’
})
Q: 如何重置store状态?
const store = useStore()
store.$reset() // 重置到初始状态
Q: 多个store如何互相调用?
// 在action中
const userStore = useUserStore()
const cartStore = useCartStore()
cartStore.checkout(userStore.currentUser)
生态推荐
pinia-plugin-persistedstate - 状态持久化
pinia-orm - ORM风格操作
vue-devtools - 官方调试工具支持