Vue · 68/70
1. Composition API 逻辑复用 2. 微信小程序与 Vue 的区别 3. React Fiber 架构与 Vue 的设计差异 4. 渐进式框架的理解 5. React 和 Vue 的技术差异 6. React 和 Vue 的区别 7. setup 中获取组件实例 8. SPA 首屏加载优化 9. 单页应用如何提高加载速度 10. 模板预编译原理 11. 什么是虚拟DOM 12. Vite 的实现原理 13. VNode 的属性 14. Vue 组件中的原生事件监听器需要手动销毁吗 15. Vue 数组元素修改与视图更新 16. Vue 项目中封装 axios 17. 打破 Vue scoped 样式隔离 18. Vue 组件和插件的区别 19. Vue 组件通信方式 20. 虚拟 DOM 的实现原理 21. Computed 与 Watch 对比 22. Vue 项目跨域解决方案 23. Vue CSS scoped 的实现原理 24. Vue 组件渲染过程 25. Vue 自定义指令的使用场景 26. Vue data 为什么必须是函数 27. Vue 项目部署与 404 问题解决 28. Vue 组件错误统一监听 29. Vue Diff 算法:Vue2 vs Vue3 30. 手写 Vue 事件机制 31. Vue 中定义全局方法 32. Vue 框架理解 33. Vue.nextTick 原理与应用 34. Vue Mixin 的理解与应用 35. Vue2 对象新增属性不响应 36. Vue.observable 实现响应式状态管理 37. Vue 父组件监听子组件生命周期 38. Keep-Alive 实现原理 39. Vue 生命周期钩子 40. Vue 项目优化实践 41. Vue 性能优化 42. Vue 权限管理实现方案 43. Vue 大型项目的结构和组件划分 44. ref、toRef、toRefs 的区别与使用场景 45. Vue 渲染过程 46. Vue-Router 路由模式原理 47. Vue SSR 服务器端渲染实现 48. v-for 中 key 的作用 49. Vue slot 插槽的使用 50. Vue 模板编译原理 51. v-model 参数用法 52. v-if 与 v-show 区别 53. Vue 版本性能分析 54. Vue 1.x 响应式系统 55. Vue 2.x 响应式系统与组件更新 56. Vue2 数组变化检测的限制与解决方案 57. Vue2 响应式原理 58. Composition API vs Options API 59. Vue3 设置全局变量 60. watch 与 watchEffect 的区别 61. Vue3 响应式原理与优势 62. Vue 3 Proxy 响应式与性能优化 63. Vue3 实现 Modal 组件 64. Vuex 辅助函数的使用 65. Vue 3 的 Tree Shaking 特性 66. Vuex 数据刷新丢失问题 67. Vue3 新特性 68. Vuex 与 Pinia 状态管理 69. Vuex 的五种属性及其作用 70. Vuex 是什么?

Vuex 与 Pinia 状态管理

Vue 状态管理库的使用与原理对比

问题

解释 Vuex 和 Pinia 的状态管理原理,包括 State、Getter、Mutation、Action 的作用和使用方式。

解答

Vuex 基本概念

Vuex 是 Vue 2/3 的集中式状态管理库,采用单向数据流。

// store/index.js
import { createStore } from 'vuex'

const store = createStore({
  // State: 存储应用状态
  state() {
    return {
      count: 0,
      todos: []
    }
  },

  // Getters: 计算派生状态(类似计算属性)
  getters: {
    doubleCount(state) {
      return state.count * 2
    },
    completedTodos(state) {
      return state.todos.filter(todo => todo.done)
    },
    // 可以访问其他 getter
    completedCount(state, getters) {
      return getters.completedTodos.length
    }
  },

  // Mutations: 同步修改状态的唯一方式
  mutations: {
    increment(state) {
      state.count++
    },
    addTodo(state, todo) {
      state.todos.push(todo)
    },
    setTodos(state, todos) {
      state.todos = todos
    }
  },

  // Actions: 处理异步操作,提交 mutation
  actions: {
    async fetchTodos({ commit }) {
      const res = await fetch('/api/todos')
      const todos = await res.json()
      commit('setTodos', todos)
    },
    // action 可以调用其他 action
    async addTodoAsync({ commit, dispatch }, todo) {
      await fetch('/api/todos', {
        method: 'POST',
        body: JSON.stringify(todo)
      })
      commit('addTodo', todo)
    }
  }
})

export default store
<!-- 组件中使用 -->
<template>
  <div>
    <p>Count: {{ count }}</p>
    <p>Double: {{ doubleCount }}</p>
    <button @click="increment">+1</button>
    <button @click="fetchTodos">加载</button>
  </div>
</template>

<script>
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'

export default {
  computed: {
    // 映射 state
    ...mapState(['count', 'todos']),
    // 映射 getters
    ...mapGetters(['doubleCount', 'completedTodos'])
  },
  methods: {
    // 映射 mutations
    ...mapMutations(['increment', 'addTodo']),
    // 映射 actions
    ...mapActions(['fetchTodos'])
  }
}
</script>

Pinia 基本概念

Pinia 是 Vue 3 推荐的状态管理库,API 更简洁,移除了 Mutation。

// stores/counter.js
import { defineStore } from 'pinia'

// Option Store 写法
export const useCounterStore = defineStore('counter', {
  state: () => ({
    count: 0,
    todos: []
  }),

  getters: {
    doubleCount: (state) => state.count * 2,
    completedTodos: (state) => state.todos.filter(t => t.done)
  },

  actions: {
    // 直接修改状态,无需 mutation
    increment() {
      this.count++
    },
    async fetchTodos() {
      const res = await fetch('/api/todos')
      this.todos = await res.json()
    }
  }
})

// Setup Store 写法(更灵活)
export const useCounterStore = defineStore('counter', () => {
  // state
  const count = ref(0)
  const todos = ref([])

  // getters
  const doubleCount = computed(() => count.value * 2)

  // actions
  function increment() {
    count.value++
  }

  async function fetchTodos() {
    const res = await fetch('/api/todos')
    todos.value = await res.json()
  }

  return { count, todos, doubleCount, increment, fetchTodos }
})
<!-- 组件中使用 -->
<template>
  <div>
    <p>Count: {{ counter.count }}</p>
    <p>Double: {{ counter.doubleCount }}</p>
    <button @click="counter.increment()">+1</button>
  </div>
</template>

<script setup>
import { useCounterStore } from '@/stores/counter'
import { storeToRefs } from 'pinia'

const counter = useCounterStore()

// 解构时保持响应式
const { count, doubleCount } = storeToRefs(counter)
// actions 可以直接解构
const { increment } = counter
</script>

响应式原理

// 简化版 Pinia 实现原理
function defineStore(id, options) {
  return function useStore() {
    // 单例模式:同一个 store 只创建一次
    if (!storeMap.has(id)) {
      const store = createStore(id, options)
      storeMap.set(id, store)
    }
    return storeMap.get(id)
  }
}

function createStore(id, options) {
  // 使用 reactive 创建响应式 state
  const state = reactive(options.state())

  // getters 转换为 computed
  const getters = {}
  Object.keys(options.getters || {}).forEach(key => {
    getters[key] = computed(() => options.getters[key](state))
  })

  // actions 绑定 this 到 store
  const actions = {}
  Object.keys(options.actions || {}).forEach(key => {
    actions[key] = options.actions[key].bind({ ...state, ...getters })
  })

  return reactive({
    ...state,
    ...getters,
    ...actions
  })
}

Vuex vs Pinia 对比

特性VuexPinia
Mutation必须通过 mutation 修改无,直接在 action 中修改
TypeScript支持较弱完整类型推断
模块化需要 modules 配置天然多 store
体积~10KB~1KB
DevTools支持支持
Vue 版本2 & 33(有 Vue 2 插件)

关键点

  • State: 响应式数据源,通过 reactive() 实现
  • Getter: 派生状态,基于 computed() 实现缓存
  • Mutation (Vuex): 同步修改状态的唯一方式,便于 DevTools 追踪
  • Action: 处理异步逻辑,Pinia 中可直接修改状态
  • Pinia 优势: 无 mutation、更好的 TS 支持、更小体积、更简洁 API