Haoyuan's blog Haoyuan's blog
首页
导航站
  • Java基础

    • Java基础
    • Java集合
    • Java反射
    • JavaJUC
    • JavaJVM
  • Java容器

    • JavaWeb
  • Java版本新特性

    • Java新特性
  • SQL 数据库

    • MySQL
    • Oracle
  • NoSQL 数据库

    • Redis
    • ElasticSearch
  • 数据库

    • MyBatis
    • MyBatis-Plus
  • 消息中间件

    • ActiveMQ
    • RabbitMQ
    • RocketMQ
    • Kafka
  • 进阶服务

    • Nginx
  • Spring
  • Spring Boot
  • Spring Security
  • Spring Cloud
  • 设计模式
  • 算法
  • 知识
  • 管理

    • Maven
    • Git
  • 部署

    • Linux
    • Docker
    • Jenkins
    • Kubernetes
  • 进阶

    • TypeScript
  • 框架

    • React
    • Vue2
    • Vue3
  • 轮子工具
  • 项目工程
  • 友情链接
  • 本站

    • 分类
    • 标签
    • 归档
  • 我的

    • 收藏
    • 关于
留言区
GitHub (opens new window)

Somnus Haoyuan

Word is cheap, show me the code.
首页
导航站
  • Java基础

    • Java基础
    • Java集合
    • Java反射
    • JavaJUC
    • JavaJVM
  • Java容器

    • JavaWeb
  • Java版本新特性

    • Java新特性
  • SQL 数据库

    • MySQL
    • Oracle
  • NoSQL 数据库

    • Redis
    • ElasticSearch
  • 数据库

    • MyBatis
    • MyBatis-Plus
  • 消息中间件

    • ActiveMQ
    • RabbitMQ
    • RocketMQ
    • Kafka
  • 进阶服务

    • Nginx
  • Spring
  • Spring Boot
  • Spring Security
  • Spring Cloud
  • 设计模式
  • 算法
  • 知识
  • 管理

    • Maven
    • Git
  • 部署

    • Linux
    • Docker
    • Jenkins
    • Kubernetes
  • 进阶

    • TypeScript
  • 框架

    • React
    • Vue2
    • Vue3
  • 轮子工具
  • 项目工程
  • 友情链接
  • 本站

    • 分类
    • 标签
    • 归档
  • 我的

    • 收藏
    • 关于
留言区
GitHub (opens new window)
  • 超文本标记语言 - Html

  • 解释编程语言 - JavaScript

  • JS 超集语言 - TypeScript

  • 界面构建框架 - React

  • 渐进式框架 - Vue2

    • Vue2 - 基础
    • Vue2 - 生命周期
    • Vue2 - 组件
    • Vue2 - Vuex
      • 什么是 Vuex
      • 概念
      • 何时使用?
      • 搭建vuex环境
      • 基本使用
      • getters的使用
      • 四个map方法的使用
        • 为什么使用这些方法?
        • mapState 方法
        • mapGetters 方法
        • mapActions方法
        • mapMutations方法
        • 完整 Demo
      • 模块化和命名空间
        • 使用
        • 获取
      • 组件仍然保有局部状态
    • Vue2 - Vue路由
  • 渐进式框架 - Vue3

  • 前端
  • 渐进式框架 - Vue2
Haoyuan
2022-07-27
目录

Vue2 - Vuex

  • 什么是 Vuex
  • 概念
  • 何时使用?
  • 搭建vuex环境
  • 基本使用
  • getters的使用
  • 四个map方法的使用
    • 为什么使用这些方法?
    • mapState 方法
    • mapGetters 方法
    • mapActions方法
    • mapMutations方法
    • 完整 Demo
  • 模块化和命名空间
    • 使用
    • 获取
  • 组件仍然保有局部状态

# 什么是 Vuex

首先知道什么是单向数据流,也就是一个数据只会被一个组件使用,即这个数据不是「共享」的,当我们需要一些数据是全局的,能被所有组件使用,那么这就是「共享资源」,这时单向数据流的简洁性很容易被破坏:

  • 多个视图依赖于同一状态
  • 来自不同视图的行为需要变更同一状态

对于问题一,传参的方法对于多层嵌套的组件将会非常繁琐,并且对于兄弟组件间的状态传递无能为力。对于问题二,我们经常会采用父子组件直接引用或者通过事件来变更和同步状态的多份拷贝。以上的这些模式非常脆弱,通常会导致无法维护的代码。

因此,我们为什么不把组件的共享状态抽取出来,以一个全局单例模式管理呢?在这种模式下,我们的组件树构成了一个巨大的「视图」,不管在树的哪个位置,任何组件都能获取状态或者触发行为。

通过定义和隔离状态管理中的各种概念并通过强制规则维持视图和状态间的独立性,我们的代码将会变得更结构化且易维护。

这就是 Vuex 背后的基本思想。

# 概念

在 Vue 中实现集中式状态(数据)管理的一个 Vue 插件,对 Vue 应用中多个组件的共享状态进行集中式的管理(读/写),也是一种组件间通信的方式,且适用于任意组件间通信。

前面的 全局事件总线(GlobalEventBus) 能实现这个效果,但是它是基于 Vue 实例本身创建的一片空间,这样可能让 Vue 实例压力很大,所以可以使用 Vuex,并且 Vuex 不仅有全局事件总线的功能,也有其他优秀的功能。

# 何时使用?

多个组件需要共享数据时,但是如果不是开发大型单页应用,使用 Vuex 可能是繁琐冗余的。

# 搭建vuex环境

安装 Vuex,命令:

npm install vuex@next --save
# 或者
yarn add vuex@next --save
1
2
3

创建文件:src/store/index.js

// 引入 Vue 核心库
import Vue from 'vue'
// 引入 Vuex
import Vuex from 'vuex'
// 应用 Vuex 插件
Vue.use(Vuex)

// 准备 actions 对象:响应组件中用户的动作
const actions = {}
// 准备 mutations 对象:修改 state 中的数据
const mutations = {}
// 准备 state 对象——保存具体的数据
const state = {}

// 创建并暴露 store
export default new Vuex.Store({
	actions,
	mutations,
	state
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

在 main.js 中创建 vm 时传入 store 配置项

// 引入 store
import store from './store'

// 创建 vm
new Vue({
	el:'#app',
	render: h => h(App),
	store
})
1
2
3
4
5
6
7
8
9

# 基本使用

初始化数据、配置 actions、配置 mutations,操作文件 store.js。

更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。

// 引入 Vue 核心库
import Vue from 'vue'
// 引入 Vuex
import Vuex from 'vuex'
// 引用 Vuex
Vue.use(Vuex)

const actions = {
    // 响应组件中加的动作
	jia(context, value){
		// console.log('actions中的jia被调用了',miniStore,value)
		context.commit('JIA', value)
        console.log('state 的值:', context.state.sum)
	},
}

const mutations = {
    // 执行加
	JIA(state, value){
		// console.log('mutations中的JIA被调用了',state,value)
		state.sum += value
	}
}

// 初始化数据
const state = {
   sum:0
}

// 创建并暴露 store
export default new Vuex.Store({
	actions,
	mutations,
	state,
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

组件中读取 Vuex 中的数据:

this.$store.state.sum // 方法里读取
{{ $store.state.sum }}  // 标签里读取
1
2

组件中修改 Vuex 中的数据,即调用 Action 的方法:

$store.dispatch('action中的方法名', 数据)
// 或
$store.commit('mutations中的方法名', 数据)
1
2
3

一个简单的 Demo,使用上面的 Vuex:

<template>
	<div>
		<h1>当前求和为:{{$store.state.sum}}</h1>
		<select v-model.number="n">
			<option value="1">1</option>
			<option value="2">2</option>
			<option value="3">3</option>
		</select>
		<button @click="increment">+</button>
	</div>
</template>

<script>
	export default {
		name:'Count',
		data() {
			return {
				n:1, // 用户选择的数字
			}
		},
		methods: {
			increment(){
				this.$store.commit('JIA',this.n)
			}
		},
		mounted() {
			console.log('Count',this.$store.state.sum)
		},
	}
</script>

<style lang="css">
	button{
		margin-left: 5px;
	}
</style>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

备注:若没有网络请求或其他业务逻辑,组件中也可以越过 actions,即不写 dispatch,直接编写 commit

# getters的使用

概念:当 state 中的数据需要经过加工后再使用时,可以使用 getters 加工。

在 store.js 中追加 getters 配置



























 
 
 
 
 






 


// 该文件用于创建 Vuex 中最为核心的 store
import Vue from 'vue'
// 引入Vuex
import Vuex from 'vuex'
// 应用 Vuex 插件
Vue.use(Vuex)

// 准备 actions:用于响应组件中的动作
const actions = {
	jia(context,value){
		console.log('actions中的jia被调用了')
		context.commit('JIA',value)
	}
}
// 准备 mutations:用于操作数据(state)
const mutations = {
	JIA(state,value){
		console.log('mutations中的JIA被调用了')
		state.sum += value
	}
}
// 准备 state:用于存储数据
const state = {
	sum:0 // 当前的和
}
// 准备 getters:用于将 state 中的数据进行加工
const getters = {
	bigSum(state){
		return state.sum * 10
	}
}

// 创建并暴露 store
export default new Vuex.Store({
	actions,
	mutations,
	state,
	getters
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39

组件中读取数据:

$store.getters.bigSum
1

如果想传参给 getters 的方法,那么 getter 应该写为:

const state = {
	sum:0
}
const getters = {
    bigSum: (state) => (num) => {
        return state.sum * num
    }
}
1
2
3
4
5
6
7
8
$store.getters.bigSum(5)
1

# 四个map方法的使用

# 为什么使用这些方法?

首先我们知道,如果组件想用 Vuex 的 state 数据,那么需要通过 this.$store.state.xxx 获取,假设 Veux 很多的 state 数据,那么我们需要写很多个 this.$store.state,这样就影响代码的美观。我们明明只需要 xxx 数据,却每次都要写 this.$store.state 前缀,这样体验非常不好,于是我们期待存在一个工具,当我们在读取 Vuex 的 state 数据时,只需要写 xxx 数据名,就自动在前面加上 this.$store.state 前缀,这个工具就是本内容介绍的四个 map 方法,Vuex 已经内置了它们。

通过 Vuex 里引入对应的 map 方法

import {mapState,mapGetters,mapActions,mapMutations} from 'vuex'
1

# mapState 方法

用于帮助我们映射 state 中的数据为计算属性,这样这些数据就绑定在组件里,可以直接通过名字使用

<script>
	import {mapState,mapGetters} from 'vuex'
	export default {
		name:'Count',
		computed:{
			// 靠程序员自己亲自去写计算属性,会出现大量的 this.$store.state 前缀
			/* sum(){
				return this.$store.state.sum
			},
			school(){
				return this.$store.state.school
			},
			subject(){
				return this.$store.state.subject
			}, */

			// 借助 mapState 生成计算属性,从 state 中读取数据。(对象写法)
			// ...mapState({he: 'sum', xuexiao: 'school', xueke: 'subject'}),

			// 借助 mapState 生成计算属性,从 state 中读取数据。(数组写法)
			...mapState(['sum','school','subject']),
		},
		mounted() {
			const x = mapState({he:'sum',xuexiao:'school',xueke:'subject'})
			console.log(x)
		},
	}
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

这样 sum、school、subject 等数据就能直接通过 this.xxx 使用。

对象写法的 key 是自己规定的名字,value 则是 Vuex 的 state 数据,这样我们使用的应该是自己规定的 key,就能获取 Vuex 的 state 数据,也就是取别名。

数组写法,自动将 key 作为 Vuex 的 state 数据的 key。

# mapGetters 方法

用于帮助我们映射 getters 中的数据为计算属性

computed: {
    // 借助 mapGetters 生成计算属性:bigSum(对象写法)
    ...mapGetters({bigSum: 'bigSum'}),

    // 借助 mapGetters 生成计算属性:bigSum(数组写法)
    ...mapGetters(['bigSum'])
},
1
2
3
4
5
6
7

# mapActions方法

用于帮助我们生成与 actions 对话的方法,即:包含 $store.dispatch(xxx) 的函数

<script>
	import {mapState,mapGetters,mapMutations,mapActions} from 'vuex'
	export default {
		name:'Count',
		data() {
			return {
				n:1, //用户选择的数字
			}
		},
		methods: {
			// 程序员亲自写方法
			/* incrementOdd(){
				this.$store.dispatch('jiaOdd',this.n)
			},
			incrementWait(){
				this.$store.dispatch('jiaWait',this.n)
			}, */

			// 借助 mapActions 生成对应的方法,方法中会调用 dispatch 去联系 actions(对象写法)
			...mapActions({incrementOdd:'jiaOdd',incrementWait:'jiaWait'})

			// 借助 mapActions 生成对应的方法,方法中会调用 dispatch 去联系 actions(数组写法)
			// ...mapActions(['jiaOdd','jiaWait'])
		}
	}
</script>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

# mapMutations方法

用于帮助我们生成与 mutations 对话的方法,即:包含 $store.commit(xxx) 的函数。

methods:{
    // 靠 mapActions 生成:increment、decrement(对象形式)
    ...mapMutations({increment:'JIA',decrement:'JIAN'}),
    
    // 靠 mapMutations 生成:JIA、JIAN(对象形式)
    ...mapMutations(['JIA','JIAN']),
}
1
2
3
4
5
6
7

备注:mapActions 与 mapMutations 使用时,若需要传递参数需要:在模板中 绑定事件时传递好参数,否则参数是事件对象。

# 完整 Demo

<template>
	<div>
		<h1>当前求和为:{{sum}}</h1>
		<h3>当前求和放大10倍为:{{bigSum}}</h3>
		<h3>我在{{school}},学习{{subject}}</h3>
		<select v-model.number="n">
			<option value="1">1</option>
			<option value="2">2</option>
			<option value="3">3</option>
		</select>
		<button @click="increment(n)">+</button>
		<button @click="decrement(n)">-</button>
		<button @click="incrementOdd(n)">当前求和为奇数再加</button>
		<button @click="incrementWait(n)">等一等再加</button>
	</div>
</template>

<script>
	import {mapState,mapGetters,mapMutations,mapActions} from 'vuex'
	export default {
		name:'Count',
		data() {
			return {
				n:1, // 用户选择的数字
			}
		},
		computed:{
			// 借助 mapState 生成计算属性,从 state 中读取数据。(对象写法)
			// ...mapState({he:'sum',xuexiao:'school',xueke:'subject'}),

			// 借助 mapState 生成计算属性,从 state 中读取数据。(数组写法)
			...mapState(['sum','school','subject']),

			/* ******************************************************************** */

			// 借助 mapGetters 生成计算属性,从 getters 中读取数据。(对象写法)
			// ...mapGetters({bigSum:'bigSum'})
			
			// 借助 mapGetters 生成计算属性,从 getters 中读取数据。(数组写法)
			...mapGetters(['bigSum'])

		},
		methods: {
			// 程序员亲自写方法
			/* increment(){
				this.$store.commit('JIA',this.n)
			},
			decrement(){
				this.$store.commit('JIAN',this.n)
			}, */

			// 借助 mapMutations 生成对应的方法,方法中会调用 commit 去联系 mutations(对象写法)
			...mapMutations({increment:'JIA',decrement:'JIAN'}),

			// 借助 mapMutations 生成对应的方法,方法中会调用 commit 去联系 mutations(数组写法)
			// ...mapMutations(['JIA','JIAN']),

			/* ************************************************* */

			// 程序员亲自写方法
			/* incrementOdd(){
				this.$store.dispatch('jiaOdd',this.n)
			},
			incrementWait(){
				this.$store.dispatch('jiaWait',this.n)
			}, */

			// 借助 mapActions 生成对应的方法,方法中会调用 dispatch 去联系 actions(对象写法)
			...mapActions({incrementOdd:'jiaOdd',incrementWait:'jiaWait'})

			// 借助 mapActions 生成对应的方法,方法中会调用 dispatch 去联系 actions(数组写法)
			// ...mapActions(['jiaOdd','jiaWait'])
		},
		mounted() {
			const x = mapState({he:'sum',xuexiao:'school',xueke:'subject'})
			console.log(x)
		},
	}
</script>

<style lang="css">
	button{
		margin-left: 5px;
	}
</style>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85

# 模块化和命名空间

上面只是写了一个 store.js 文件作为 Vuex 的使用,但是实际开发中,会有很多的组件,这样 store.js 会有大量的数据和方法,有 a.vue 要用到的,也有 b.vue 用的,这样就会导致 store.js 内容大量冗余,所以我们可以把某些组件用到的数据放到一个 js 文件,另一些组件用到的数据放到另一个 js 文件,实现隔离效果。

目的:让代码更好维护,让多种数据分类更加明确。

# 使用

修改 store.js

// Count 组件用的数据
const countAbout = {
  namespaced:true, // 开启命名空间
  state:{x:1},
  mutations: { ... },
  actions: { ... },
  getters: {
    bigSum(state){
       return state.sum * 10
    }
  }
}
// Person 组件用的数据
const personAbout = {
  namespaced:true, // 开启命名空间
  state:{ ... },
  mutations: { ... },
  actions: { ... }
}

const store = new Vuex.Store({
  modules: {
    countAbout,
    personAbout
  }
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

上面将 Count、Person 组件用的数据放到 store.js,这样如果有多个组件,那么 store.js 会越来越「拥挤」,所以我们创建两个 Vuex 管理的 js 文件,然后把这两个 js 文件放到 store.js 进行引入。

store 文件夹
|—— count.js
|—— person.js
|—— store.js / index.js
1
2
3
4

count.js

// 求和相关的配置
export default {
	namespaced:true,
	actions:{
		jiaOdd(context,value){
			console.log('actions中的jiaOdd被调用了')
			if(context.state.sum % 2){
				context.commit('JIA',value)
			}
		},
		jiaWait(context,value){
			console.log('actions中的jiaWait被调用了')
			setTimeout(()=>{
				context.commit('JIA',value)
			},500)
		}
	},
	mutations:{
		JIA(state,value){
			console.log('mutations中的JIA被调用了')
			state.sum += value
		},
		JIAN(state,value){
			console.log('mutations中的JIAN被调用了')
			state.sum -= value
		},
	},
	state:{
		sum:0, // 当前的和
		school:'可乐',
		subject:'前端',
	},
	getters:{
		bigSum(state){
			return state.sum*10
		}
	},
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

person.js

// 人员管理相关的配置
import axios from 'axios'
import { nanoid } from 'nanoid'
export default {
	namespaced:true,
	actions:{
		addPersonWang(context,value){
			if(value.name.indexOf('王') === 0){
				context.commit('ADD_PERSON',value)
			}else{
				alert('添加的人必须姓王!')
			}
		},
		addPersonServer(context){
			axios.get('https://api.uixsj.cn/hitokoto/get?type=social').then(
				response => {
					context.commit('ADD_PERSON',{id:nanoid(),name:response.data})
				},
				error => {
					alert(error.message)
				}
			)
		}
	},
	mutations:{
		ADD_PERSON(state,value){
			console.log('mutations中的ADD_PERSON被调用了')
			state.personList.unshift(value)
		}
	},
	state:{
		personList:[
			{id:'001',name:'张三'}
		]
	},
	getters:{
		firstPersonName(state){
			return state.personList[0].name
		}
	},
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41

最后在 store.js 引入上面两个 js 文件(一般 store.js 改为 index.js,更有标识性)

// 该文件用于创建 Vuex 中最为核心的 store
import Vue from 'vue'
// 引入 Vuex
import Vuex from 'vuex'
import countOptions from './count'
import personOptions from './person'
// 应用Vuex插件
Vue.use(Vuex)

// 创建并暴露store
export default new Vuex.Store({
	modules:{
		countAbout: countOptions,
		personAbout: personOptions
	}
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

# 获取

  1. 开启命名空间后,组件中读取 state 数据:

    // 方式一:自己直接读取
    this.$store.state.personAbout.list
    // 方式二:借助 mapState 读取
    ...mapState('countAbout',['sum','school','subject']),
    
    1
    2
    3
    4
  2. 开启命名空间后,组件中读取 getters 数据:

    // 方式一:自己直接读取
    this.$store.getters['personAbout/firstPersonName']
    // 方式二:借助 mapGetters 读取
    ...mapGetters('countAbout',['bigSum'])
    
    1
    2
    3
    4
  3. 开启命名空间后,组件中调用 dispatch

    // 方式一:自己直接 dispatch
    this.$store.dispatch('personAbout/addPersonWang',person)
    // 方式二:借助 mapActions
    ...mapActions('countAbout',{incrementOdd:'jiaOdd',incrementWait:'jiaWait'})
    
    1
    2
    3
    4
  4. 开启命名空间后,组件中调用 commit

    // 方式一:自己直接 commit
    this.$store.commit('personAbout/ADD_PERSON',person)
    // 方式二:借助 mapMutations
    ...mapMutations('countAbout',{increment:'JIA',decrement:'JIAN'}),
    
    1
    2
    3
    4

# 组件仍然保有局部状态

使用 Vuex 并不意味着你需要将 所有的 状态放入 Vuex。虽然将所有的状态放到 Vuex 会使状态变化更显式和易调试,但也会使代码变得冗长和不直观。如果有些状态严格属于单个组件,最好还是作为组件的局部状态。你应该根据你的应用开发需要进行权衡和确定。

编辑此页 (opens new window)
#Vue
更新时间: 2025/04/06, 01:04:59
Vue2 - 组件
Vue2 - Vue路由

← Vue2 - 组件 Vue2 - Vue路由→

最近更新
01
技术随笔 - Element Plus 修改包名 原创
11-02
02
Reactor - 扩展性
11-02
03
Reactor - 最佳实践
11-02
更多文章>
Theme by Vdoing | Copyright © 2021-2025 Somnus Haoyuan | MIT License
京公网安备 11010802034042号 京ICP备2025120692号-1
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式