In the vue project, multiple data concurrent requests

1. Project background

When writing a project, there are several drop-down box data that need to be obtained through fixed interfaces. Each interface needs to send a request and write a method for data processing. I just thought of using the all() method of axios

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

Multiple requests are required at one time. Use the axios.all() and axios.spread() methods to implement the function of concurrent execution and reception of multiple requests. Both areThe static method of axios is not an instance method and can be called directly usingaxios

Note that if an error occurs in one of the multiple requests, subsequent requests will no longer be executed.

3. Code part

This is in the request.js file. By the way, the post request get request of axios is written.

Get requests are divided into json format and form format

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. Use

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

Guess you like

Origin blog.csdn.net/a99101/article/details/133308325