组合 action
- Action 中通常放的都是异步的请求,如何知道 action 什么时候结束?
- 首先,你需要明白 store.dispatch 可以处理被触发的 action 的处理函数返回的 Promise,并且 store.dispatch 仍旧返回 Promise:
举例子
- 本页面有个 input 输入框,需要将 input 中的内容传给后台,并且更新 state 中的数据再清楚 input 框中的内容
<input v-mode="text" />
cosnt actions={
addItem({commit},text) {
axios.get('/todos',{text:text}).then(res=> {
commit('addItem',text)
})
}
}
export default {
addItem() {
this.$store.dispatch("addItem", this.text);
this.text = "";
},
};
2. 解决方法:
方法一、
- 将 this.text=""以函数的方式传递给 action,action 在 commit 之后执行
cosnt actions={
addItem({commit},payload) {
axios.get('/todos',{text:payload.text}).then(res=> {
commit('addItem',payload.text)
payload.callback()
})
}
}
this.$store.dispatch("addItem", {
text: this.text,
callback: () => (this.text = ""),
});
方法二
- action 中返回一个 promise 实例,在 promise 中确定 this.text=’'的执行时机
const actions = {
addItem({ commit }, text) {
return new Promise((resolve) => {
axios.get("/todos", { text: payload.text }).then((res) => {
commit("addItem", payload.text);
resolve();
});
});
},
};
this.$store.dispatch("addItem", this.text).then((res) => {
this.text = "";
});
方法三
- 利用 await 在 async 执行完后执行原理
const actions = {
async addItem({ commit }, text) {
axios.get("/todos", { text: payload.text }).then((res) => {
commit("addItem", payload.text);
});
},
};
export default {
methods:{
async addItem() {
await this.$store.dispatch('addItem',this.text)
this.text=""
}
}
}
});