代码之家  ›  专栏  ›  技术社区  ›  Ready Dev

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

  •  10
  • Ready Dev  · 技术社区  · 7 年前

    在axios和vue中使用多个请求如何并行?

    2 回复  |  直到 6 年前
        1
  •  23
  •   Saikat SHASHANK HONRAO    5 年前

    因为React和Vue可以使用axios,所以它的代码基本相同。

    一定要阅读 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' })
        }
      }
    }
    
        2
  •  2
  •   omarjebari    5 年前

    您可以将异步调用传递给Promise。全部的 只要他们每个人都返回一个承诺,他们就会同时执行。 我在用商店。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');
            });
    }