Vuex于2015年推出,作为Vue应用的官方状态管理方案。它以Flux架构为灵感,通过单一状态树管理所有组件状态,引入了严格的单向数据流、突变(Mutations)和动作(Actions)等概念。
// Vue 2 + Vuex示例
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
}
})
Vuex最初为Vue 2设计,随着Vue 3的推出及TypeScript的普及,Vuex 4虽然兼容了Vue 3,但其内部架构仍基于Vue 2时代的设计理念。
Pinia最初是2019年作为Vuex 5的概念验证而开发的实验性项目,由Vue核心团队成员Eduardo San Martin Morote创建。随着项目成熟,Pinia在2021年底获得官方推荐,成为Vue生态系统的新一代状态管理库。
// Vue 3 + Pinia示例
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0
}),
actions: {
increment() {
this.count++
},
async incrementAsync() {
setTimeout(() => this.increment(), 1000)
}
},
getters: {
doubleCount: (state) => state.count * 2
}
})
Vue官方团队推出Pinia的主要原因包括:
Vuex在Vue 2时代设计,随着Vue 3的全新架构,Vuex的一些设计理念与Vue 3不够匹配:
随着前端开发复杂度增加,开发者对工具的期望也在提高:
Vue 3带来了Composition API等革命性变化,状态管理库需要与之保持一致:
Pinia显著简化了状态管理的API:
// Vuex需要mutations和actions
// Vuex示例
const store = new Vuex.Store({
state: { count: 0 },
mutations: {
increment(state) { state.count++ }
},
actions: {
incrementAsync({ commit }) {
setTimeout(() => commit('increment'), 1000)
}
}
})
// Pinia合并了mutations和actions
// Pinia示例
const useCounterStore = defineStore('counter', {
state: () => ({ count: 0 }),
actions: {
increment() { this.count++ },
async incrementAsync() {
setTimeout(() => this.increment(), 1000)
}
}
})
主要简化点:
Pinia从设计之初就考虑TypeScript支持,提供完整的类型推导:
// Pinia的TypeScript支持
import { defineStore } from 'pinia'
interface User {
id: string;
name: string;
email: string;
}
export const useUserStore = defineStore('user', {
state: () => ({
user: null as User | null,
users: [] as User[]
}),
getters: {
// 完美的类型推导
userCount: (state) => state.users.length,
// 使用this访问其他getter时仍有类型支持
hasUsers(): boolean {
return this.userCount > 0
}
},
actions: {
// 类型安全的actions
async fetchUser(id: string) {
this.user = await api.getUser(id)
}
}
})
// 使用时也有完整类型推导
const userStore = useUserStore()
const count = userStore.userCount // 类型为number
const user = userStore.user // 类型为User | null
TypeScript优势:
Pinia设计之初就考虑与Vue 3的Composition API集成:
// 在组件中使用Pinia
import { useCounterStore } from '@/stores/counter'
export default {
setup() {
const counterStore = useCounterStore()
// 可以直接解构,并保持响应性
const { count, doubleCount } = storeToRefs(counterStore)
// 可以直接调用actions
function handleClick() {
counterStore.increment()
}
return { count, doubleCount, handleClick }
}
}
或者在中更简洁地使用:
Count: {{ count }}
Double: {{ doubleCount }}
集成优势:
Pinia提供了出色的开发工具体验:
Pinia采用store概念替代Vuex的模块系统,每个store都是独立的:
// 用户相关的store
export const useUserStore = defineStore('user', {
state: () => ({ /* ... */ }),
actions: { /* ... */ }
})
// 购物车相关的store
export const useCartStore = defineStore('cart', {
state: () => ({ /* ... */ }),
actions: { /* ... */ }
})
// 可以在不同store之间相互使用
export const useCheckoutStore = defineStore('checkout', {
state: () => ({ /* ... */ }),
actions: {
async checkout() {
const userStore = useUserStore()
const cartStore = useCartStore()
// 使用多个store的数据
if (userStore.isLoggedIn && cartStore.items.length > 0) {
// 执行结账逻辑
}
}
}
})
模块化优势:
Pinia相比Vuex具有显著的体积和性能优势:
假设我们要实现一个用户认证功能,对比Vuex和Pinia的实现方式:
// Vuex实现用户认证
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
user: null,
token: localStorage.getItem('token') || null,
loading: false,
error: null
},
getters: {
isAuthenticated: state => !!state.token,
currentUser: state => state.user
},
mutations: {
SET_LOADING(state, loading) {
state.loading = loading
},
SET_ERROR(state, error) {
state.error = error
},
SET_USER(state, user) {
state.user = user
},
SET_TOKEN(state, token) {
state.token = token
if (token) {
localStorage.setItem('token', token)
} else {
localStorage.removeItem('token')
}
}
},
actions: {
async login({ commit }, credentials) {
try {
commit('SET_LOADING', true)
commit('SET_ERROR', null)
const { token, user } = await api.login(credentials)
commit('SET_TOKEN', token)
commit('SET_USER', user)
return true
} catch (error) {
commit('SET_ERROR', error.message)
return false
} finally {
commit('SET_LOADING', false)
}
},
async logout({ commit }) {
try {
commit('SET_LOADING', true)
await api.logout()
commit('SET_TOKEN', null)
commit('SET_USER', null)
} catch (error) {
commit('SET_ERROR', error.message)
} finally {
commit('SET_LOADING', false)
}
}
}
})
// Pinia实现用户认证
import { defineStore } from 'pinia'
interface User {
id: string;
name: string;
email: string;
}
interface AuthState {
user: User | null;
token: string | null;
loading: boolean;
error: string | null;
}
export const useAuthStore = defineStore('auth', {
state: (): AuthState => ({
user: null,
token: localStorage.getItem('token'),
loading: false,
error: null
}),
getters: {
isAuthenticated: (state) => !!state.token,
currentUser: (state) => state.user
},
actions: {
async login(email: string, password: string) {
this.loading = true
this.error = null
try {
const { token, user } = await api.login(email, password)
this.token = token
this.user = user
localStorage.setItem('token', token)
return true
} catch (error) {
this.error = error.message
return false
} finally {
this.loading = false
}
},
async logout() {
this.loading = true
try {
await api.logout()
this.token = null
this.user = null
localStorage.removeItem('token')
} catch (error) {
this.error = error.message
} finally {
this.loading = false
}
}
}
})
Vuex在Vue 2组件中使用:
Pinia在Vue 3组件中使用:
Pinia版本更加简洁、直观且类型安全。
Pinia的API设计使得从Vuex迁移相对简单:
安装Pinia:替换Vuex依赖
npm uninstall vuex
npm install pinia
配置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:将Vuex模块转换为Pinia store
以提供的add-modal.vue
组件为例,如果使用状态管理来处理其表单逻辑,Pinia将提供更简洁的实现:
// 使用Pinia管理表单状态
import { defineStore } from 'pinia'
import type { FormDataType } from '../types'
import { viewType } from '../type'
export const useFormStore = defineStore('keyEnergyForm', {
state: () => ({
formData: {
companyName: '',
// ...其他表单字段
} as FormDataType,
loading: false,
operationLogs: [],
// ...其他状态
}),
getters: {
title: (state) => {
if (state.type === viewType.DETAIL && state.formData.companyName) {
return state.formData.companyName
}
return state.customTitle
}
},
actions: {
async initIndustryTree() {
// 初始化行业树逻辑
},
async getDetail(id: string) {
if (!id || this.type !== viewType.DETAIL) return
this.loading = true
try {
// 获取详情数据
} catch (error) {
// 错误处理
} finally {
this.loading = false
}
},
async handleSubmit() {
// 表单提交逻辑
}
}
})
随着Vue生态系统的发展,Pinia的地位和功能也在不断增强:
Vue官方团队推出Pinia是基于多种因素的战略决策:
Pinia代表了Vue生态系统状态管理的未来方向,通过提供更简洁、更类型安全、更符合现代JavaScript最佳实践的API,帮助开发者构建更可维护的应用。对于大多数项目,特别是新项目,Pinia是当前的最佳选择。