aurora blog
  • JS

    • 基本汇总
    • Date时间
    • Array方法
    • String 方法
    • Object方法
    • RegExp正则
    • Es6 新特性等
    • Event-Loop
    • Http and Https
    • for in和for of区别
    • Web Worker
    • Promise && async
    • 堆内存 & 栈内存
    • JS设计模式探索
    • npm & yarn
    • Fetch和Axios的区别
    • 学习及面试问题整理
    • URL 输入到页面加载过程
    • 跨域&nginx本地项目代理
  • FE框架

    • react

      • 基本用法
      • react生命周期
      • hooks 16.8版本后
      • Route原理
      • Redux源码解析
      • React16 Fiber
      • React-VirtualDOM
      • React事件委托机制
    • vue

      • vue 基本用法
      • vue 生命周期
      • VirtualDOM
      • vue 事件委托
      • vue 架构
      • vue 状态管理
      • 问题等
    • React-Native

      • React-Native 基本用法
    • 微前端

      • 遇到的问题
    • 鸿蒙 harmony

      • harmony 基础
  • 构建工具

    • webpack

      • Webpack配置详解
      • Webpack的使用
      • Babel-polyfill
      • webpack面试题
    • vite

      • vite基本配置
  • Typescript

    • Typescript详解
  • Servers

    • Nodejs
    • Nginx
  • Git命令

    • git常用规范
  • 数据库

    • mongodb
    • mongodb
  • Other

    • Jenkins自动化部署

Vue 状态管理方案整理

  • 1. Vuex(Vue2/Vue3均支持)
  • 2. Pinia(Vue3 推荐)
  • 3. 简单状态管理(小型项目)
  • 总结

1. Vuex(Vue2/Vue3均支持)

Vuex 是 Vue 官方推荐的集中式状态管理库,适合中大型项目。

核心概念:State、Getter、Mutation、Action、Module

// store.js
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);

export default new Vuex.Store({
  state: { count: 0 },
  mutations: {
    increment(state) { state.count++; }
  },
  actions: {
    incrementAsync({ commit }) {
      setTimeout(() => { commit('increment'); }, 1000);
    }
  },
  getters: {
    doubleCount: state => state.count * 2
  }
});

组件中使用:

this.$store.state.count
this.$store.commit('increment')
this.$store.dispatch('incrementAsync')
this.$store.getters.doubleCount

2. Pinia(Vue3 推荐)

Pinia 是 Vue3 官方推荐的新一代状态管理库,API 更简洁,类型支持更好。

// store/counter.js
import { defineStore } from 'pinia';

export const useCounterStore = defineStore('counter', {
  state: () => ({ count: 0 }),
  getters: {
    doubleCount: (state) => state.count * 2
  },
  actions: {
    increment() { this.count++; }
  }
});

组件中使用:

import { useCounterStore } from '@/store/counter';
const counter = useCounterStore();
counter.increment();
console.log(counter.doubleCount);

3. 简单状态管理(小型项目)

对于简单场景,可以直接用 Vue 的响应式 API 管理状态,无需引入 Vuex/Pinia。

// store.js
import { reactive } from 'vue';
export const state = reactive({ count: 0 });

组件中使用:

import { state } from './store';
state.count++;

总结

  • Vue2 推荐 Vuex,Vue3 推荐 Pinia。
  • Pinia 更轻量、类型友好,API 更现代。
  • 小型项目可直接用响应式 API 管理状态,无需专门库。

更多内容可参考

最近更新:: 2025/8/7 15:46
Contributors: liyulai
Prev
vue 架构
Next
问题等