在调用异步函数之前,请等待提交事件完成



我想在表单完成提交后运行一个异步函数。表单更新了一个购物车,我需要在添加产品后从购物车中获取产品。

我已经尝试了一百万种方法,似乎没有什么能等到表单完成提交后再运行我的代码。我不想使用任何计时事件。

这是我拥有的最新版本的代码。它们都做同样的事情,并在提交完成之前运行:

window.addEventListener(
'submit', 
() => vueFreshie.$options.components['fresh-credit'].options.methods.getCart(), 
false
)
window.addEventListener("submit", async e => {
await vueFreshie.$options.components['fresh-credit'].options.methods.getCart()
}, false)

这是我正在调用的Vue方法,为了示例起见,我对它进行了简化。

methods: {
async getCart() {
let response = await axios.get(`/cart.js`)
debugger
}
}

该方法被称为fine,只是太早了,cart还没有更新。

开始:我使用了onSubmit事件处理程序来监听表单提交&axios显式地将数据发布到我的服务器。通过这种方式,我可以对提交请求进行更多的控制,并且我可以在继续使用getCartAPI之前await完成提交请求。

new Vue({
el: "#app",
data: () => {
return {
formData: {
firstName: '',
lastName: ''
}
}
},
methods: {
async onSubmit() {
const {data} = await axios.post('https://jsonplaceholder.typicode.com/posts', this.formData);
console.log('response from submitted request', data);
await this.getCart();
},
async getCart() {
console.log('safe to call the get cart API now');
const {data} = await axios.get('https://jsonplaceholder.typicode.com/posts');
console.log('response from cart api', data);
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<div id="app">
<form v-on:submit.prevent="onSubmit">
<input name="firstName" v-model="formData.firstName"><br/>
<input name="lastName" v-model="formData.lastName">
<button type="submit">SUBMIT</button>
</form>
</div>

参考
  • Vue中的事件处理

最新更新