【发布时间】:2018-11-05 11:53:31
【问题描述】:
如何使用 axios 和 vue 并行发出多个请求?
【问题讨论】:
如何使用 axios 和 vue 并行发出多个请求?
【问题讨论】:
您可以将异步调用传递给 Promise.all。 只要他们每个人都返回一个承诺,他们就会同时执行。 我正在使用 store.dispatch,但您同样可以使用 axios 调用或 fetch。
在这个例子中,我在创建 vue 组件时进行调用:
...
async created() {
const templates = this.$store.dispatch(TEMPLATES_LOAD);
const userTemplates = this.$store.dispatch(USER_TEMPLATES_LOAD);
const players = this.$store.dispatch(OTHER_PLAYERS_LOAD);
return await Promise.all([templates, userTemplates, players])
.then(() => {
console.log('Loaded data for form elements');
});
}
【讨论】:
因为 axios 可以被 React 和 Vue 使用,所以代码几乎是一样的。
请务必阅读axios docs,您可以从那里了解。
不管怎样,我给你举个例子:
<template>
<div>
<button @click="make_requests_handler">Make multiple request</button>
{{message}} - {{first_request}} - {{second_request}}
</div>
</template>
还有脚本:
import axios from 'axios'
export default {
data: () => ({
message: 'no message',
first_request: 'no request',
second_request: 'no request'
}),
methods: {
make_requests_handler() {
this.message = 'Requests in progress'
axios.all([
this.request_1(), //or direct the axios request
this.request_2()
])
.then(axios.spread((first_response, second_response) => {
this.message = 'Request finished'
this.first_request = 'The response of first request is' + first_response.data.message
this.second_request = 'The response of second request is' + second_response.data.message
}))
},
request_1() {
this.first_request: 'first request began'
return axios.get('you_URL_here')
},
request_2() {
this.second_request: 'second request began'
return axios.get('another_URL', { params: 'example' })
}
}
}
【讨论】:
axios.all 可能未定义。请改用原生 ES6 Promise.all。
all 将延迟较快的调用,直到最慢的调用完成。
then 块中,您可以处理这两个响应。在这里阅读更多 -> github.com/axios/axios/issues/371