Vuex-核心概念3—actions
mutations 中是同步代码,要操作异步代码则要在 actions 中
如果在 mutations 中有进行异步操作,那么页面会刷新,但数据不会在 state 对象中改变
Vuex-状态管理的目录结构,转战Vuex 状态管理模式-项目结构
Vuex-核心概念1,转战state+getters
Vuex-核心概念2,转战mutations
Vuex-核心概念4,转战modules
1、错误代码示例
state: {
info: {
name: 'Tom',
age: 100,
height: 1.92
}
},
mutations: {
updateInfo (state) {
state.info.name = 'Jery'
// 错误写法
//setTimeOut(() => {
// state.info.name = 'Jery'
//})
}
}
2、要在 actions 中处理异步代码
/*
* context:上下文,相当于 state
*/
actions: {
aUpdateInfo (context) {
setTimeOut(() => {
context.commit('updateInfo')
}, 1000)
}
}
- 组件中使用,使用方法
this.$store.dispatch
methods: {
aUpdateInfoAdd () {
this.$store.dispatch('aUpdateInfo ')
}
}
3、如果调用了异步操作后,需要异步代码返回一个结果,告诉调用的地方已经完成了异步操作,可以对返回结果进行一些处理
使用 Promise()
actions: {
aUpdateInfo (context, payload) {
// 把异步操作放到 Promise () 中
return new Promise((resolve, reject) => {
setTimeOut(() => {
// 调用 mutations
context.commit('updateInfo')
resolve(111) // 成功的回调,then()
}, 1000)
})
}
}
- 组件中使用
<h2>{{$store.state.info}}</h2>
<button @click="aUpdateInfoAdd">修改信息</button>
<script>
export default {
methods: {
aUpdateInfoAdd () {
this.$store.dispatch('aUpdateInfo').then(res => {
console.log('异步操作已经完成')
console.log(res) // 111
})
}
}
}
</script>
——————————————————————————————
“连太阳都没法做到让每个人满意,何况我只是一枚小小的人儿啊 ”