vue使用axios.all()解决并发多个请求-QUI-Notes

vue在安装了axios之后(vue请求数据及安装使用axios教程),我们就要调接口数据,一个两个接口的还可以这样写:

getRec () {
      let that = this
      let api = 'http://localhost:3000/personalized?limit=12'
      this.$axios.get(api).then((response) => {
        console.log(response.data)
        that.recList = response.data.result
      }).catch(function (error) {
        that.pageErr = true
        that.errMsg = error
      })
},
getBanner () {
      let that = this
      let api = 'http://localhost:3000/banner'
      this.$axios.get(api).then((response) => {
        that.bannerFlag = true
        that.bannerIndex = response.data.banners
      }).catch(function (error) {
        that.pageErr = true
        that.errMsg = error
      })
}

100个这样的请求还这样写?是不是太麻烦了?

单独一个函数,单独调用,数据单独请求,一个页面可能有10个请求,也有可能有100个,在初始化的时候,需要初始化一堆调用函数,非常麻烦,那么就需要用axios.all()和axios.spread()解决高并发的请求了。

axios.all()的使用方法:

1.单独函数调用各自请求接口

getrec () {
      let api = 'http://localhost:3000/personalized'
      return this.$axios({
        url: api,
        method: 'GET',
        params: {
          limit: 12
        }
      })
},
getBanner () {
      let api = 'http://localhost:3000/banner'
      return this.$axios({
        url: api,
        method: 'GET'
      })
}

2.mounted挂载时调用axios.all()方法

mounted () {
    var that = this
    this.$axios.all([that.getBanner(), that.getrec()])
        .then(this.$axios.spread(function (res1, res2) {
          console.log('请求1', res1)
          console.log('请求2', res2)
          //绑数据 that指向data数据
        })).catch((err) => {
         //捕获错误
        })
}

酱紫就可以解决页面高并发接口请求的问题了。拒绝无效代码,做高效分享 —— 我是陈小知。