Vuex
# Vuex的认识与使用
# 什么是Vuex?
⚙️ 官方: Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式 + 库。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。 🙅♂ 自我理解: 集中存储应用程序大范围所用到的数据,状态等等。
# 安装Vuex
点击查看代码
npm 方式: npm install vuex@next --save
yarn 方式:yarn add vuex@next --save
1
2
2
注意
在安装的时候注意版本号。vue2用vuex3!官方目前默认vuex4
# Vuex的五大核心概念
- State
- Action
- Mutation
- Module
- Getter
# 1. State
State提供唯一的公共数据源,所有共享的数据都要统一放到Store的State中进行存储。
1
const store= new Vuex.Store({
state: { count: 0 }
})
1
2
3
2
3
# (1.1) 组件中访问State中数据的第一种方式
⚙️ this.$store.state.全局数据名称
注意
注意在{{}} 双大括号中就不用在加this了
# (1.2) 组件中访问State中数据的第二种方式
⚙️
import {mapState} from 'vuex'
//计算机属性
computed: {
...mapState(['count'])
}
//使用
{{count}}即可
1
2
3
4
5
6
7
2
3
4
5
6
7
# 2. Mutation
Mutation用于变更Store中的数据。只能通过Mutation更改Store中的数据,不能直接操作Store中的数据。
1
const store= new Vuex.Store({
state: { count: 0 },
mutations: {
add(state){
state.count++;
}
}
})
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# (2.1) 组件中访问Mutation中的方法第一种方式
⚙️ this.$store.commit('方法名')
# (2.2) 组件中访问Mutation中的方法第二种方式
⚙️
import {mapMutations} from 'vuex'
methods: {
//使用
...mapMutations(['add']),
adds(){
this.add();
}
}
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# (2.3) 组件中访问Mutation中的方法传参方式
⚙️
const store= new Vuex.Store({
state: { count: 0 },
mutations: {
add(state,parameter){
state.count+=parameter;
}
}
})
// 方式一调用
this.$store.commit('add',3);
// 方式二调用
...mapMutations(['add']),
adds(){
this.add(3);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 3. Action
Action 用于处理异步任务,必须通过Action而不能使用Mutation。在Action中还要通过触发Mutation的方式间接变更数据。
1
const store= new Vuex.Store({
state: { count: 0 },
mutations: {
add(state){
state.count++;
}
},
actions:{
addAsyns(context){
setTimeout(() =>{
context.commit('add')
})
}
}
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
注意
在action中不能直接修改state中的数据。必须通过触发某个mutation。
# (3.1) 组件中触发Action的第一种方式
⚙️ this.$store.dispatch('方法名')
# (3.2) 组件中触发Action第二种方式
⚙️
import {mapActions} from 'vuex'
methods: {
//使用
...mapActions(['addAsyns']),
adds(){
this.addAsyns();
}
}
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# 3. Getter
Getter 用于对Store中的数据进行加工处理形成新的数据,并不会修改原数据,只起到一个包装的作用。
1
const store= new Vuex.Store({
state: { count: 0 },
mutations: {
add(state){
state.count++;
}
},
actions:{
addAsyns(context){
setTimeout(() =>{
context.commit('add')
})
}
},
getters:{
countGetter: state => state.count
}
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# (3.1) 组件中使用Getters的第一种方式
⚙️ this.$store.getters.countGetter
# (3.2) 组件中使用Getters的第二种方式
⚙️
import {mapGetters} from 'vuex'
computed: {
//使用
...mapGetters(['countGetter']),
}
1
2
3
4
5
2
3
4
5
编辑 (opens new window)
上次更新: 2022/10/09, 14:24:13