如何使用axios和vue并行发出多个请求?

推荐答案

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

一定要读axios docs,你可以从那里理解.

不管怎样,我要给你们展示一个例子:

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

还有 playbook :

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

Vue.js相关问答推荐

如何 for each 动态创建的按钮/文本字段设置唯一变量?

何时将代码拆分为 Nuxt 中的组件?

Nuxt 2.15.7 的构建错误 - 无法解析 CSS @font-face URL

在 bootstrap-vue 中渲染自定义样式

Vuex Mutations 和 Airbnb eslint

如何在Typescript语言Vuejs中使用watch功能?

如何为 Vue 应用提供 robots.txt

VueJS:向左,元素的顶部位置?

在基于 TypeScript 的 Vue 中将 vuex 状态和Mutations绑定到复选框组件属性

自定义props类型

Amazon EC2 错误:监听 EACCES 0.0.0.0:80

我可以在 Vue 实例方法中传播的 mapMutations 中使用this吗?

Vue 3 组合 API,如何在 setup() 函数中获取上下文父属性?

删除一行后刷新 Bootstrap-Vue 表

如何避免在 Vue 中一直写 this.$store.state.donkey 的需要?

Vue cli 在 css 中构建生产更改不透明度

使用 axios 和 vue.js 取消先前的请求

组件已注册但未使用 vue/no-unused-components

根据nuxt中的url参数动态加载组件

禁用外部主题文件产生的 Dart SASS 警告