vue项目中,多个数据并发请求

1、项目背景

在写项目时候,有好几个下拉框数据是需要通过固定接口获取的,每一个接口都需要发送一次请求写一个方法进行数据处理。就想到看采用axios的all()方法

2、axios.all()和axios.spread()

一次需要多个请求,使用axios.all()axios.spread()方法可以实现多请求并发执行并接收的功能,两者都是axios的静态方法,不是实例方法,可直接使用axios调用

注意,如果多个请求中某个请求发生错误,会导致后续请求也不再执行

3、代码部分

这个是在request.js文件中,顺带把axios的post请求get请求给写了

get请求分为json格式和表单格式

import axios from 'axios'
Vue.prototype.$http = axios // 并发请求


const $axios = axios.create({
  // 设置超时时间
  timeout: 3000,
  // 基础url,会在请求url中自动添加前置链接
  baseURL: 'xxxxxxxxxx'
})

// get,post请求方法
export default {
  post(url, data) {
    return $axios({
      method: 'post',
      url,
      data: Qs.stringify(data),
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
      }
    })
  },
  post2(url, data) {
    return $axios({
      method: 'post',
      url,
      data: data,
      headers: {
        'Content-Type': 'application/json'
      }
    })
  },
  get(url, params) {
    return $axios({
      method: 'get',
      url,
      params
    })
  }
}

4、使用

mounted() {
    this.getAgentList()
  },  
methods: {
    // 获取a,b,c
    getAgentList() {
      // queryA().then((res) => {
      //   if (res.success == true) {
      //     console.log(res);
      //     this.xxx = res.data;
      //   }
      // });
      // queryB().then((res) => {
      //   if (res.success == true) {
      //     this.XXXXX = res.list;
      //   }
      // });
      // queryC().then((res) => {
      //   if (res.success == true) {
      //     this.C = res.list;
      //   }
      // });

      this.$http
        .all([
          queryA(),
          queryB(),
          queryC()
        ])
        .then(
          this.$http.spread((res1, res2, res3) => {
            console.log(res3)
            this.A = res1.data
            this.B = res2.list
            this.C = res3.list
          })
        )
    },
}

猜你喜欢

转载自blog.csdn.net/a99101/article/details/133308325