当前位置: 首页 > news >正文

Vuex 详细用法(Vue2 和 Vue3)

Vuex 详细用法(Vue2 和 Vue3)

Vuex 是 Vue.js 官方推荐的状态管理库,用于集中管理应用中所有组件的共享状态。本文将详细介绍 Vuex 在 Vue2 和 Vue3 中的用法。

1. Vuex 核心概念

1.1 核心概念概述

无论是在 Vue2 还是 Vue3 中,Vuex 的核心概念都包括:

  • State:存储应用的状态数据
  • Getters:从 state 中派生的计算属性
  • Mutations:唯一可以修改 state 的方法(同步)
  • Actions:处理异步操作,可以提交 mutations
  • Modules:将 store 分割成模块

1.2 Vue2 和 Vue3 中的主要区别

  • Vue2:使用 Vue.use(Vuex) 安装插件
  • Vue3:使用 createStore API 创建 store
  • 组合式 API:Vue3 推荐使用组合式 API 与 Vuex 配合

2. Vue2 中的 Vuex 用法

2.1 安装 Vuex

npm install vuex@3 --save  # Vue2 通常使用 Vuex 3.x

2.2 创建 Store

// store/index.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) {return state.count * 2}}
})

2.3 在 Vue 实例中注入 Store

// main.js
import Vue from 'vue'
import App from './App.vue'
import store from './store'new Vue({store,render: h => h(App)
}).$mount('#app')

2.4 组件中使用 Vuex

// 组件中使用
export default {computed: {count() {return this.$store.state.count},doubleCount() {return this.$store.getters.doubleCount}},methods: {increment() {this.$store.commit('increment')},incrementAsync() {this.$store.dispatch('incrementAsync')}}
}

3. Vue3 中的 Vuex 用法

3.1 安装 Vuex

npm install vuex@4 --save  # Vue3 通常使用 Vuex 4.x

3.2 创建 Store

// store/index.js
import { createStore } from 'vuex'export default createStore({state: {count: 0},mutations: {increment(state) {state.count++}},actions: {incrementAsync({ commit }) {setTimeout(() => {commit('increment')}, 1000)}},getters: {doubleCount(state) {return state.count * 2}}
})

3.3 在 Vue 实例中注入 Store

// main.js
import { createApp } from 'vue'
import App from './App.vue'
import store from './store'const app = createApp(App)
app.use(store)
app.mount('#app')

3.4 组件中使用 Vuex

选项式 API
// 组件中使用(选项式 API)
export default {computed: {count() {return this.$store.state.count},doubleCount() {return this.$store.getters.doubleCount}},methods: {increment() {this.$store.commit('increment')},incrementAsync() {this.$store.dispatch('incrementAsync')}}
}
组合式 API
// 组件中使用(组合式 API)
import { computed } from 'vue'
import { useStore } from 'vuex'export default {setup() {const store = useStore()const count = computed(() => store.state.count)const doubleCount = computed(() => store.getters.doubleCount)const increment = () => {store.commit('increment')}const incrementAsync = () => {store.dispatch('incrementAsync')}return {count,doubleCount,increment,incrementAsync}}
}

4. 模块化 Store

4.1 创建模块

// store/modules/counter.js
const state = {count: 0
}const mutations = {increment(state) {state.count++}
}const actions = {incrementAsync({ commit }) {setTimeout(() => {commit('increment')}, 1000)}
}const getters = {doubleCount(state) {return state.count * 2}
}export default {namespaced: true,  // 启用命名空间state,mutations,actions,getters
}

4.2 注册模块

// store/index.js
import { createStore } from 'vuex'
import counter from './modules/counter'export default createStore({modules: {counter}
})

4.3 使用模块

Vue2 中使用命名空间模块
// 组件中使用
export default {computed: {count() {return this.$store.state.counter.count},doubleCount() {return this.$store.getters['counter/doubleCount']}},methods: {increment() {this.$store.commit('counter/increment')},incrementAsync() {this.$store.dispatch('counter/incrementAsync')}}
}
Vue3 中使用命名空间模块
// 组合式 API 中使用
import { computed } from 'vue'
import { useStore } from 'vuex'export default {setup() {const store = useStore()const count = computed(() => store.state.counter.count)const doubleCount = computed(() => store.getters['counter/doubleCount'])const increment = () => {store.commit('counter/increment')}const incrementAsync = () => {store.dispatch('counter/incrementAsync')}return {count,doubleCount,increment,incrementAsync}}
}

5. 最佳实践

5.1 状态管理原则

  1. 单一状态树:整个应用只有一个 store
  2. 状态是只读的:只能通过 mutations 修改状态
  3. mutations 是同步的:异步操作放在 actions 中

5.2 模块化组织

store/
├── index.js          # 主 store 文件
├── modules/
│   ├── user.js       # 用户模块
│   ├── product.js    # 产品模块
│   └── ...
└── types.js          # 类型定义(可选)

5.3 使用 map 辅助函数(Vue2)

import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'export default {computed: {...mapState({count: state => state.counter.count}),...mapGetters(['counter/doubleCount'])},methods: {...mapMutations({increment: 'counter/increment'}),...mapActions(['counter/incrementAsync'])}
}

5.4 TypeScript 支持(Vue3)

// store/index.ts
import { createStore } from 'vuex'interface State {count: number
}export default createStore({state(): State {return {count: 0}},mutations: {increment(state: State) {state.count++}},// ...其他选项
})

6. 总结

  1. Vue2 和 Vue3 的主要区别

    • Vue2 使用 new Vuex.Store()
    • Vue3 使用 createStore()
    • Vue3 推荐使用组合式 API 与 Vuex 配合
  2. 核心概念

    • State、Getters、Mutations、Actions、Modules
  3. 模块化

    • 使用命名空间组织大型应用
    • 便于维护和扩展
  4. 最佳实践

    • 遵循状态管理原则
    • 合理组织 store 结构
    • Vue3 中考虑 TypeScript 支持

pp

http://www.dtcms.com/a/477651.html

相关文章:

  • 注册公司网站如何注册黑龙江公共资源交易网官网
  • 如何将iPhone上的HEIF图像下载到电脑
  • 欧洲宇航局使用Varjo XR头戴设备为宇航员提供虚拟现实空间站任务训练
  • iphone IOS3~IOS9游戏 旧iphone 单机游戏合集分享
  • 昂瑞微冲刺科创板:硬科技与资本市场的双向奔赴
  • 从入门到精通【Redis】Redis 典型应⽤ --- 缓存 (cache)
  • 【深入理解计算机网络10】UDP协议详解
  • 宁波网站建设模板制作什么叫优化
  • 自动裁剪图(电商使用)
  • 大模型应用开发
  • 第15题 三数之和
  • 【1015】计算并联电阻的阻值
  • 红黑树实现与原理剖析(上篇):核心规则与插入平衡逻辑
  • 【AES加密专题】8.实战-测试加密网站和代码
  • 收费的电影网站怎么做可以打开任何网站的软件
  • 设计广告网站wordpress怎么换空间
  • React 18并发模式解析:Fiber架构与性能优化技巧
  • 火山引擎多媒体实验室画质理解大模型Q-Insight入选NeurIPS 2025 Spotlight
  • 【StarRocks】-- DATETIME 与 TIMESTAMP 区别详解
  • k8s nginx ingress介绍
  • 深入starrocks-怎样实现多列联合统计信息
  • 无锡百度网站推广廊坊seo优化排名
  • 小程序如何接入火山引擎埋点数据
  • 汝阳网站建设哪家好旅游社网站建设规划书
  • Qt MSVC_64bit在Release模式下调试与WinDbg调试exe
  • Flutter鸿蒙开发
  • 《Qt应用开发》笔记p2
  • 保定网站建设与seo贵州快速整站优化
  • SOLIDWORKS转换为3DXML全流程技术指南:附迪威模型网在线方案
  • 【Java Xml】Apache Commons Digester3解析