当mutation属性里面需要用到异步操作时,我们不能够直接在mutation直接使用异步操作,而是需要使用到actions属性来改变,如图:
updateinfo(state){
state.stu[0].name = 'zhubin'
}
},
actions:{
aupdate(context,payload){
return new Promise ((resolve,reject)=>{
setTimeout(()=>{
context.commit('updateinfo')
console.log(payload);
resolve('111')
},1000)
})
}
},
用context.commit提交,并且在组件使用dispatch来获取actions属性里的方法,如图:
update(){
this.$store.dispatch('aupdate','payload').then(res=>{
console.log('打印成功');
console.log(res);
})
}
并且可以传递参数payload。且vuex对原先已经存在封装好的state属性值已经做好响应式处理,即发生数据变换时会自动在vue组件里面更新。