1、什么是vuex?
实现组件全局状态(数据)管理的一种机制,可以方便实现组件之间的数据共享(类似全局变量)
2、好处:
1、集中管理数据,方便开发
2、能够高效的实现组件之间的数据共享
3、存储的数据是响应式的,可以实时保持数据与页面的同步
3、安装vuex,官网有详细的教程
4、核心概念
1、state:提供唯一的公共数据源,所有共享的数据都要统一放到store的state中进行存储
访问state中数据的方式:
一:this.$store.state.全局数据名称(最常用的方式)
二:从vuex中倒入mapState函数,import { mapState } from ‘vuex’
将全局数据映射为当前组件的计算属性
computed:{
...mapState(['count'])
}
2、mutations: 用于变更store中的数据
1、只能通过mutation变更store数据,不可以在也买你或者组件中直接操作数据
2、通过这种方法苏染繁琐,但是可以集中监控所有数据的变化
mutations:{
方法(state){
state.全局变量的变化操作
}
}
在页面或者组件调用mutations的方法:
this.$store.commit(‘方法名’)
可以在mutations时传递参数:
mutations:{
方法(state,step){
state.全局变量的变化操作
step就是调用方法时传递的数据
}
}
调用时:this.$store.commit(‘方法名’,step)
触发mutations的第二种方式:
1、从vuex中倒入mapMutations 函数
import { mapMutations } from ‘vuex’
2、将指定的mutations函数映射为当前页面或者组件的methods函数
...mapMuattions(['方法一',‘方法二’,‘。。。’])
3、注意:在mutations函数中不能写异步的代码
3、Action: 用于处理一步的任务
如果通过异步的方式变更数据,必须通过Action,不能使用mutations ,但是在Action中还是要触发mutations的方式间接的变更数据
actions:{
//context 相当于new出来的一个实力对象
funcAsync(context) {
异步操作,调用mutations的方法
content.commit(‘方法名’)
}
}
调用的方式:
methods:{
func(){
this.$store.dispatch('funcAsync')
}
}
参数:
funcAsync(context,step) {
异步操作,调用mutations的方法
content.commit(‘方法名’)
}
this.$store.dispatch('funcAsync',step)
触发Actions的第二种方式:
1、在vuex中导入mapActions函数
import { mapActions } from ‘vuex’
2、通过导入的mapActions函数,将actions函数映射为当前组件的methods方法:
methods:{
...mapActions(['funcAsync','方法二','其他方法'])
}
4、Getter:用于对store中的数据进行加工处理形成新的数据
1、Getter可以对Store中已有的数据加工形成新的数据,类似Vue的计算属性
2、Store中数据发生变化,Getter的数据也会跟着变化
getters:{
showNum(state) {
return state.全局变量值操作
}
}
调用第一种方式
thiis.$store.getters.名称
第二种方式:
import { mapGetters } from ‘vuex’
computed:{
...mapGetters(['方法名'])
}