一、概述
1、什么是Vuex
Vuex是实现全局状态(数据)管理的一种机制,可以方便管理组件之间数据的共享
2、使用Vuex的好处
- 集中管理共享的数据,易于开发和后期维护
- 能够高效的实现组件之间的数据共享,提高开发效率
- 存在Vuex中的数据都是响应式的,实时保持数据和页面的同步
3、什么样的数据适合存到Vuex中
一般情况下 存组件之间共享的数据。
私有数据 存到data属性中
二、安装Vuex
npm install vuex --save
三、核心概念
1、State
State提高唯一的公共数据源,所有共享的数据都要统一的存放到Store的State中进行存储
state: {
count:0
},
组件访问State中共享数据方式:
①this.$store.state.全局数据名称
注意:在template组件中 this可以省略
②
从Vuex中按需导入 mapState函数
import {mapState} from 'vuex'
通过刚才导入的mapState函数,将当前组件需要的全局数据,映射为当前组件的computed计算属性
computed:{
...mapState(['count'])
}
2、Mutation
用于变更Store中的数据,集中监控数据的变化。vuex不允许在组件中直接操作Store改变数据
①方式一:
mutations: {
add(state){ //上面的state对象
//变更状态
state.count++;
}
},
使用:
methods: {
btnHandler1() {
this.$store.commit('add');
},
mutation转递参数:
mutations: {
add(state){ //上面的state对象
//变更状态
state.count++;
},
addN(state,step){
//变更状态
state.count+=step;
}
},
methods: {
btnHandler1() {
this.$store.commit('add');
},
btnHandlerN(){
this.$store.commit('addN',3);
}
},
①方式二:
按需导入函数 mapMutations
import {mapMutations} from 'vux'
通过刚才导入的函数 映射当前组件的methods方法中
methods: {
...mapMutations(["sub"]),
btnHandler1() {
this.sub()
},
},
3、Action
用于处理异步操作
注意:在mutation中不能执行异步代码
如需使用 异步操作 则使用Action
方式一:
actions: {
addAsync(context) {
//延时1s执行
// 不能直接修改state中的数据
// 必须通过 context.commit() 去触发某个mutation
setTimeout(() => {
context.commit('add');
}, 1000)
}
},
btnHandlerA(){
//dispatch函数 专门用来用来触发action
this.$$store.dispatch('addAsync');
}
可以看出 只有mutation有修改state的权利
方式二:
导入mapActions函数
import {mapActions} from "vuex";
将指定的actions函数映射为当前组件的methods函数
methods: {
...mapMutations(["sub"]),
...mapActions(['subAsync']),
btnHandler1() {
this.sub()
},
btnHandler2(){
this.subAsync()
}
},
4、Getter
对store里的数据进行加工处理,但是不会改变原来的数据
当store中的数据发送变化 Getter中的数据也会方式变化
getters:{
showNum:state=>{
return '当前最新的数据量值为【'+state.count+'】'
}
},
使用方式一:
this.$store.getters.名称
$store.getters.showNum
方式二:
导入mapGetters
import { mapGetters } from "vuex";
将改函数映射为 组件中的 computed 计算属性
computed: {
...mapState(["count"]),
...mapGetters(['showNum'])
},