vue項目中axios併發請求(axios.all & axoios.spread)

場景需求:

  1. 一個接口的參數會需要使用另一個接口獲取
  2. 兩個接口同時請求完數據加載頁面

解決方案:(axios處理併發請求的助手函數)

  1. axios.all(接口1, 接口2)
  2. axios.spread(callback1, callback2)

1、引入接口

import axios from "axios"
import {getSellerDetail} from '../../api/seller'
import {getMemberCardInfo} from '../../api/pay_online/index'  

2、處理數據

created(){
    if (this.$route.query.type){
        this.type = this.$route.query.type;
        this.sellerId = this.$route.query.targetId;
        this.initApi()
    }
},
methods: {
    initApi(){
        axios.all([
            getSellerDetail(this.sellerId),
            getMemberCardInfo(this.sellerId, this.payMoney)
        ]).then(axios.spread((sellerDetail, memberCardInfo) => {
            this.loading = false;
            // 商戶信息
            this.detail = sellerDetail.data.detail;
            this.sellerPic = this.detail.picture;
            this.sellerName = this.detail.name;
            this.discount = this.detail.discount;
            // 會員卡信息
            this.cardDetail = memberCardInfo.data;
            this.balance = this.cardDetail.balance;  //餘額
            this.rechargeTip = this.cardDetail.rechargeTip;  // 付款金額提示充值
        }))
    }
}

3、接口返回:

console.log(sellerDetail.data)
console.log(memberCardInfo.data)接口返回

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章