const store = new Vuex.Store({
state:{
name:'jjk',
age:10
},
mutations:{
change:function(state,a){
return state.name += a;
},
changeAsync:function(state,a){
console.log(state.num +=a);
}
},
getters:{
getAge:function(state){
return state.age;
}
},
actions:{
add:function(context,value){
setTimeout(function(){
//提交事件
context.commit('changeAsync',value);
},1000)
}
}
})
解读:
获取:this. s t o r e . s t a t e . n a m e ; t h i s . store.state.name;this. store.state.name;this.store.getters.getAge
修改:this. s t o r e . c o m m i t ( ′ c h a n g e ′ , 10 ) ; t h i s . store.commit('change',10);this. store.commit(′change′,10);this.store.dispatch(‘add’, 5);
四个主要属性:state;mutations;getters;actions
state
保存组件之间共享信息
直接获取:this.$store.state.name
mutations
显示的更改state里的数据
修改state信息提交:this.$store.commit(‘change’,10)
原理:调用commit方法给mutations中的方法传值
mutations中的方法默认接受两个值一个state,一个commit传进来的值
getters
获取state里的数据
获取需要的存在state的信息this.$store.getters.getAge
actions
异步提交:action中的函数作用是调用mutations中的函数提交修改数据
原理:外部出发action中函数,action中函数触发mutations中函数修改
例如:
外部出发action中的函数:this.$store.dispatch(‘add’, 5);
触发action中的add,action中的add触发mutations中的changeAsync
项目中使用
创建vuex仓库store/index.js
入口main.js
修改获取数据
获取数据
获取方式2