Vue 2 使用 Vuex 是默认选项,Vue 3 中官方推荐 Pinia 作为新一代状态管理方案。两者对比后,语法简化不少,以下记录基础用法和对比细节。
一、安装方式
Vuex 安装:
npm install vuex@4
Pinia 安装:
npm install pinia
二、基本使用对比
Vuex 示例
// store/index.js
import { createStore } from 'vuex'
const store = createStore({
state: () => ({ count: 0 }),
mutations: {
increment(state) {
state.count++
}
},
actions: {
asyncIncrement({ commit }) {
setTimeout(() => commit('increment'), 1000)
}
}
})
export default store
在 main.js
中挂载:
import { createApp } from 'vue'
import App from './App.vue'
import store from './store'
createApp(App).use(store).mount('#app')
组件中使用:
import { useStore } from 'vuex'
const store = useStore()
store.commit('increment')
Pinia 示例
// stores/counter.js
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0
}),
actions: {
increment() {
this.count++
}
}
})
在 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')
组件中使用:
import { useCounterStore } from '@/stores/counter'
const counter = useCounterStore()
counter.increment()
三、语法与体验差异
对比项 | Vuex | Pinia |
---|---|---|
使用语法 | 模块化冗长 | 简洁、函数式 |
TypeScript | 配置复杂 | 内置支持 |
响应性 | 依赖 Vuex 内部封装 | 原生响应式(ref/reactive) |
状态访问 | store.state.xxx |
直接访问变量 store.xxx |
开发体验 | 传统写法多,逻辑分散 | 更贴合 Composition API |
四、组合使用说明
Vuex 和 Pinia 不推荐混用。新项目建议直接使用 Pinia,旧项目可以逐步迁移。
五、模块拆分建议(Pinia)
多个模块建议一个 store 一个文件,按功能划分:
stores/
├── counter.js
├── user.js
├── settings.js
六、小结
Vuex 和 Pinia 都能满足 Vue 项目的状态管理需求。Pinia 在 Vue 3 中的优势是:结构清晰、语法简洁、类型支持友好,适合现代项目。