Actions的基本定义
Actions是用来对异步操作的VueX
-
组件中通过$store.dispatch传给actions
-
actions 通过commit提交给mutations
-
mutations直接修改state
components中:
<button @click="updateInfo('you')">修改信息</button>
methods
updateInfo(name) {
this.$store.dispatch('upinfo', name)
}
store/index.js
state:{
info:{
name: 'zhiou',
age: 18,
height: 1.89
}
}
actions:{
aUpdataInfo(context, name) {
setTimeout(() => {
context.commit('upinfo', name)
}, 1000)
}
}
mutations:{
upinfo(state, name){
state.info.name = name
}
}
Actions中使用Promise
store/index.js
actions:{
aUpdataInfo(context, name) {
return new Promise((resolve, reject) => {
setTimeout(() => {
context.commit('upinfo', name)
resolve('传递成功!')
}, 1000)
})
}
}
components中的methods
methods:{
updateInfo(name) {
this.$store.dispatch('aUpdataInfo', name)
.then(console.log('提交成功!'))
}
}
VueX中的Actions用于处理异步操作,组件通过$store.dispatch调用,然后通过commit传递给mutations来更新state。本文介绍了Actions的基本定义及如何结合Promise在Actions中进行异步操作。
1323

被折叠的 条评论
为什么被折叠?



