调用方法
State:this.$store.state.xxx
Mutations:this.$store.commit('xxx',aaa)
Actions:this.$store.dispatch('xxx',aaa)
Getters:this.$store.getters.xxx
State
State提供唯一的公共数据源,所有共享的数据都要统一放到Store中的State中存储
在组件中访问State的方式:
1) this.$store.state 全局数据名称 如:this.$store.state.count
2) 先按需导入mapState函数: import { mapState } from 'vuex'
然后数据映射为计算属性: computed:{ ...mapState(['全局数据名称']) }
Mutations
Mutation用于修改变更$store中的数据
使用方式:
打开store.js文件,在mutations中添加代码如下
mutations: {
add(state,step){
//第一个形参永远都是state也就是$state对象
//第二个形参是调用add时传递的参数
state.count+=step;
}
}
有两种调用方式
this.$store.commit('add',10)
//使用commit函数调用mutations中的对应函数,
//第一个参数就是我们要调用的mutations中的函数名
//第二个参数就是传递给add函数的参数
import { mapMutations } from 'vuex'
export default {
methods:{
//获得mapMutations映射的sub函数
...mapMutations(['sub']),
//当点击按钮时触发Sub函数
Sub(){
//调用sub函数完成对数据的操作
this.sub(10);
}
}
}
Actions
在mutations中不能编写异步的代码,会导致vue调试器的显示出错。
在vuex中我们可以使用Action来执行异步操作。
打开store.js文件,修改Action,如下:
actions: {
addAsync(context,step){
setTimeout(()=>{
context.commit('add',step);
},2000)
}
}
第一种方式
this.$store.dispatch('addAsync',5)
第二种方式
import { mapActions } from 'vuex'
export default {
data() {
return {}
},
methods:{
//获得mapActions映射的addAsync函数
...mapActions(['subAsync']),
asyncSub(){
this.subAsync(5);
}
}
}
Getters
Getter用于对Store中的数据进行加工处理形成新的数据。它只会包装Store中保存的数据,并不会修改Store中保存的数据,当Store中的数据发生变化时,Getter生成的内容也会随之变化。
export default new Vuex.Store({
.......
getters:{
//添加了一个showNum的属性
showNum : state =>{
return '最新的count值为:'+state.count;
}
}
})
第一种用法:
添加插值表达式使用getters
{{$store.getters.showNum}}
第二种用法:
导入mapGetters,并将之映射为计算属性
import { mapGetters } from 'vuex'
computed:{
...mapGetters(['showNum'])
}