Axios-Make multiple request at once (vue.js)

后端 未结 2 1755
攒了一身酷
攒了一身酷 2021-02-06 05:02

How to make multiple requests in parallel using axios and vue ?

相关标签:
2条回答
  • 2021-02-06 05:32

    You can pass your asynchronous calls to Promise.all. As long as each of them returns a promise they will execute at the same time. I'm using store.dispatch but you could equally use axios calls or fetch.

    In this example i'm making the calls when the vue component gets created:

    ...
    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');
            });
    }
    
    0 讨论(0)
  • 2021-02-06 05:34

    Since axios can be used by React and Vue it is pretty much the same code.

    Make sure to read axios docs, you can understand it from there.

    Anyway, I am going to show you an example:

    <template>
      <div>
       <button @click="make_requests_handler">Make multiple request</button>
       {{message}} - {{first_request}} - {{second_request}}
      </div>
    </template>
    

    And the script:

    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' })
        }
      }
    }
    
    0 讨论(0)
提交回复
热议问题