Axios - 一次发出多个请求(vue.js)

时间:2018-05-26 06:41:26

标签: vue.js vuejs2 axios

如何使用axios和vue并行创建多个请求?

2 个答案:

答案 0 :(得分:10)

  

由于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' })
    }
  }
}

答案 1 :(得分:1)

您可以将异步调用传递给Promise.all。 只要他们每个人都返回承诺,他们就会同时执行。 我正在使用store.dispatch,但您同样可以使用axios调用或访存。

在此示例中,我将在创建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');
        });
}