Pinia和Vuex区别

226 阅读1分钟

Pinia vs Vuex 全面对比

架构设计对比

Vuex 架构

Store
├── State
├── Mutations (同步)
├── Actions (异步)
└── Getters
└── Modules
                

Pinia 架构

Store
├── State
├── Actions (同步/异步合并)
└── Getters
                

核心差异对比表

对比维度Vuex 4.xPinia 2.x
Vue版本支持Vue 2/3Vue 3+
TypeScript支持需要类型声明原生完美支持
模块系统嵌套模块结构扁平化独立存储
异步处理必须通过actions可直接在actions处理
Devtools支持完整支持完整支持

模块化实现对比

Vuex 模块示例


// user模块
const userModule = {
  namespaced: true,
  state: () => ({ name: '' }),
  mutations: {
    SET_NAME(state, name) {
      state.name = name
    }
  },
  actions: {
    fetchUser({ commit }) {
      // 异步操作
    }
  }
}

// 主store
const store = createStore({
  modules: {
    user: userModule
  }
})
                

Pinia 模块示例


// stores/user.js
export const useUserStore = defineStore('user', {
  state: () => ({ name: '' }),
  actions: {
    setName(name) {
      this.name = name // 直接修改
    },
    async fetchUser() {
      // 异步操作
    }
  }
})

// 直接导入使用
import { useUserStore } from './stores/user'
                

优缺点分析

Vuex 优缺点

优点:

  • 成熟的生态系统
  • 严格的代码结构规范
  • 完善的插件系统

缺点:

  • 相对繁琐的模板代码
  • TypeScript支持需要额外配置
  • 必须区分mutations/actions

Pinia 优缺点

优点:

  • 极简的API设计
  • 完美的TypeScript支持
  • 自动代码分割

缺点:

  • 相对较新的生态(插件较少)
  • 不兼容Vue2
  • 缺少严格模式

选择建议

  • 推荐使用Pinia的情况:

    • 新启动的Vue3项目
    • 需要良好TS支持的项目
    • 希望简化状态管理的项目
  • 建议保留Vuex的情况:

    • 需要维护的Vue2项目
    • 依赖特定Vuex插件的项目
    • 大型团队需要严格规范的项目