Vuex入门

Vuex概述

Vuex是实现组件全局状态(数据)管理的一种机制,可以方便的实现组件之间的数据共享

使用Vuex管理数据的好处:

  • 能够在vuex中集中管理共享的数据,便于开发和后期进行维护
  • 能够高效的实现组件之间的数据共享,提高开发效率
  • 存储在vuex中的数据是响应式的,当数据发生改变时,页面中的数据也会同步更新

Vuex中的核心特性

state

State提供唯一的公共数据源,所有共享的数据都要统一放到Store中的State中存储

在组件中访问State的方式:

1
2
# 方式一
this.$store.state.xxx
1
2
3
# 方式二
import { mapState } from 'vuex'
computed:{ ...mapState(['全局数据名称']) } //数据映射为计算属性

Mutation

Mutation用于修改变更$store中的数据(注意不要直接在组件中操作store中的数据,而是通过Mutation操作数据)

打开store.js文件,在mutations中添加代码如下

1
2
3
4
5
6
7
mutations: {
add(state,step){
//第一个形参永远都是state也就是$state对象
//第二个形参是调用add时传递的参数
state.count+=step;
}
}

Mutation的使用方式一:

1
2
3
4
5
6
7
8
9
10
<button @click="Add">+1</button>

methods:{
Add(){
//使用commit函数调用mutations中的对应函数,
//第一个参数就是我们要调用的mutations中的函数名
//第二个参数就是传递给add函数的参数
this.$store.commit('add',10)
}
}

Mutation的使用方式二:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import { mapState,mapMutations } from 'vuex'

export default {
data() {
return {}
},
methods:{
//获得mapMutations映射的sub函数
...mapMutations(['sub']),
//当点击按钮时触发Sub函数
Sub(){
//调用sub函数完成对数据的操作
this.sub(10);
}
},
computed:{
...mapState(['count'])

}
}

Action

在mutations中不能编写异步的代码,会导致vue调试器的显示出错。
在vuex中我们可以使用Action来执行异步操作。

打开store.js文件,修改Action,如下:

1
2
3
4
5
6
7
actions: {
addAsync(context,step){
setTimeout(()=>{
context.commit('add',step);
},2000)
}
}

Action的使用方式一:

1
2
3
4
5
6
7
<button @click="AddAsync">...+1</button>

methods:{
AddAsync(){
this.$store.dispatch('addAsync',5)
}
}

Action的使用方式二:

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
import { mapState,mapMutations,mapActions } from 'vuex'

export default {
data() {
return {}
},
methods:{
//获得mapMutations映射的sub函数
...mapMutations(['sub']),
//当点击按钮时触发Sub函数
Sub(){
//调用sub函数完成对数据的操作
this.sub(10);
},
//获得mapActions映射的addAsync函数
...mapActions(['subAsync']),
asyncSub(){
this.subAsync(5);
}
},
computed:{
...mapState(['count'])

}
}

Getter

Getter用于对Store中的数据进行加工处理形成新的数据
它只会包装Store中保存的数据,并不会修改Store中保存的数据,当Store中的数据发生变化时,Getter生成的内容也会随之变化

打开store.js文件,添加getters,如下:

1
2
3
4
5
6
7
8
9
export default new Vuex.Store({
.......
getters:{
//添加了一个showNum的属性
showNum : state =>{
return '最新的count值为:'+state.count;
}
}
})

Getter的使用方式一:

1
{{$store.getters.showNum}}

Getter的使用方式二:

1
2
3
4
import { mapGetters } from 'vuex'
computed:{
...mapGetters(['showNum'])
}