说说 Pinia 与 Vuex 的区别?

Pinia 是 Vue 官方推荐的 新一代状态管理库,作为 Vuex 的"接班人",它在使用体验、类型支持、性能等方面做了大量优化。我们下面分为 ✅ 概念对比、📦 核心使用对比、🧬 源码实现机制、🎯 何时使用 Pinia 等维度全面解析。


✅ Pinia vs Vuex 核心对比

特性 Pinia Vuex(v3/v4)
是否官方维护 ✅ Vue 核心团队维护 ✅ Vue 核心团队维护
模块化支持 ✅ 原生支持多个 store ✅ 需要命名空间模块
使用方式 Composition API 风格(函数式) 选项式 API
TypeScript 支持 ✅ 极佳(自动推导) ⚠️ 一般,需要手动声明
Devtools 支持 ✅ Vue Devtools 完整集成 ✅ 支持
学习曲线 ✅ 简洁直观 ⚠️ 有点"重"
体积与性能 ✅ 更轻更快 ⚠️ 更大更复杂
Mutation ❌ 不存在 mutation,直接修改 ✅ 必须通过 mutation 修改
Store 动态注册 ✅ 更灵活、热更新友好 ⚠️ 动态模块稍麻烦
SSR 支持 ✅ 默认支持 ⚠️ 需要额外处理

📦 使用对比示例

🔹 Vuex 示例

js 复制代码
// store.js
export default new Vuex.Store({
  state: { count: 0 },
  mutations: {
    increment(state) { state.count++ }
  },
  actions: {
    asyncIncrement({ commit }) {
      setTimeout(() => commit('increment'), 1000)
    }
  }
})

🔹 Pinia 示例

js 复制代码
// useCounterStore.ts
export const useCounterStore = defineStore('counter', {
  state: () => ({ count: 0 }),
  actions: {
    increment() {
      this.count++
    },
    async asyncIncrement() {
      await new Promise(r => setTimeout(r, 1000))
      this.increment()
    }
  }
})

✅ 没有 mutations,直接在 actions 修改 state!


🧬 源码底层分析(简化理解)

1.Pinia 的核心是 defineStore()

js 复制代码
export function defineStore(id, options) {
  return function useStore() {
    const store = createSetupStore(id, options)
    return store
  }
}
  • 每次调用 useStore() 都返回当前 store 实例;
  • state 是通过 reactive() 创建的;
  • actions 是自动绑定了 this 的普通函数;
  • Pinia 底层大量使用了 Vue reactivity 包如 reactive()、effectScope() 等。

2.Vuex 的核心则是 Store 构造器

js 复制代码
class Store {
  constructor(options) {
    this._mutations = options.mutations
    this._actions = options.actions
    this._state = reactive({ data: options.state() })
  }

  commit(type, payload) {
    this._mutations[type](this.state, payload)
  }

  dispatch(type, payload) {
    return this._actions[type]({ commit, state }, payload)
  }
}

Vuex 使用了 commit() 来限制只能通过 mutations 改变 state,增强可追踪性(但使用繁琐)。


🧠 总结:为什么推荐使用 Pinia?

🎯 实际开发中优点:

  • 代码更清爽、易读
  • 没有 mutation 的繁琐模板代码
  • 支持组合式函数风格(和 Vue3 完美搭配)
  • 类型推导极佳,在 TS 项目中几乎无痛
  • 更适合大型项目拆分模块、动态注册 store、提高维护性

🔧 什么时候还用 Vuex?

  • 旧 Vue2 项目 中维护成本高,不想迁移;
  • 项目使用 Vuex 的插件系统(如持久化、状态追踪)依赖很重。

如果你项目已经在用 Vue3 + Composition API,那我 100% 推荐直接上 Pinia。

相关推荐
石小石Orz2 分钟前
模块联邦:更快的微前端方式!
前端
xiaogg36785 分钟前
网站首页菜单两种布局vue+elementui顶部和左侧栏导航
前端·vue.js·elementui
神膘护体小月半5 分钟前
bug 记录 - 使用 el-dialog 的 before-close 的坑
前端·javascript·bug
&白帝&9 分钟前
使用vite-plugin-html在 HTML 文件中动态注入数据,如元数据、环境变量、标题
前端·html·dreamweaver
SouthernWind10 分钟前
RAGFlow构建知识库和联网搜索对话平台:从零到一的完整开发指南
前端·javascript
我是小七呦15 分钟前
😧纳尼?前端也能做这么复杂的事情了?
前端·面试·ai编程
陈_杨19 分钟前
鸿蒙5开发宝藏案例分享---性能优化案例解析
前端
前端付豪21 分钟前
揭秘网易统一日志采集与故障定位平台揭秘:如何在亿级请求中1分钟定位线上异常
前端·后端·架构
香蕉可乐荷包蛋32 分钟前
vue对axios的封装和使用
前端·javascript·vue.js·axios
娃哈哈哈哈呀36 分钟前
html - <mark>标签
前端·html