vuex学习
vuex学习
vuex核心概念
State
state提供唯一的公共的数据源,所有共享的数据都要统一放到Store的State中存储。
//创建store数据源,提供唯一的公共数据
const store=new Vuex.store({
state:{count:0}
})
//组件访问State中的数据的第一种方式
this.$store.state.全局数据名称
//普通的js文件访问
import store from './store'
store.state.全局数据名称
//组件访问State中数据的第二种方式
//1.从vuex中按需导入mapState函数 写在需要使用store的组件中的script标签中去
import {mapState} from 'vuex'
//2.通过刚才导入的mapState函数,将当前组件需要的全局数据,映射为当前组件的computed计算属性:
computed:{
...mapState(['count','message'])
}
//3.使用
console.log(this.count);
Mutation(同步操作)
Mutation用于变更Store中的数据
- 只能通过mutation变更store数据,不可以直接操作store中的数据
- 通过这种方式虽然操作起来繁琐一些,但是可以集中监控所有数据的变化。
//定义Mutation
const store=new Vue.Store({
state:{
count:0
},
mutations:{
//step为参数 参数可以是对象{}
add(state,step){
//变更状态
state.count+=step;
}
}
})
//触发mutation
methods:{
handle1(){
//触发mutations的第一种方式
//commit的作用 就是调用摸个mutation函数
this.$store.commit('add',3)
}
}
//触发mutation第二种方式
//1.从vuex中按需导入mapMutation函数
import {mapMutations} from 'vuex'
//2.将指定的mutations函数,映射为当前的组件的methods方法
methods:{
...mapMutations(['add','addN']);
}
//调用
this.add();
Action(用于处理异步操作)
Action用于异步操作 。如果通过异步操作(比如定时器)改变操作数据,必须通过Action,而不能使用Mutation,但是在Action中还是要通过触发Mutation的方式间接变更数据
//定义Action
const store=new Vuex.Store({
//省略其他代码
mutations:{
addN(state,step){
state.count+=step
}
},
actions:{
addnAsync(context,step){
setTimeout(()=>{
//只能commit Mutations方法 step是形式参数
context.commit('addN',step)
},1000)
}
}
})
//触发Action
methods:{
handle(){
//触发action的第一种方式
//dispatch用于提交actions里面的方法 5是实际参数
this.$store.dispatch('addnAsync',5);
}
},
created(){
//调用
this.handle();
}
//触发actions第二种方式
import {mapActions} from 'vuex'
//通过刚才导入的mapActions函数,将需要的actions函数,映射为当前组件的methods方法
methods:{
...mapActions(['addASync','addnAsync'])
}
created:{
//调用
this.addnAsync();
}
Getter
getter用于对Store中的数据加工处理形成新的数据
- getter可以对Store中已有的数据加工处理之后形成新的数据,类似于Vue的计算属性
- store中的数据发生变化,getter的数据也会跟着变化。 但是getter不会修改store中的数据。
//定义Getter
const store=new Vuex.store({
state:{
count:0
},
getters:{
showNum:state=>{
return `当前最新的数量是${state.count}`
}
}
})
//使用getters的第一种方式
this.$store.getters.名称
{{$store.getters.showNum}}
//使用getters的第二种方式
import {mapGetters} from 'vuex'
computed:{
...mapGetters(['showNum'])
}
//调用
{{showNum}}

浙公网安备 33010602011771号