axios的cancel取消請求

我們在做項(xiàng)目的時候,為了防止一些用戶的瘋狂點(diǎn)擊,獲取是tab欄的快速切換,我們往往需要做一些防止重復(fù)提交的操作,好處就不用說了。請看代碼(使用的是axios)

var app = new Vue({
  el: '#app',
  data: {
    source: null,
    minutehchartid:'',
    endTime:'',
    startTime:'',
    currentMinutehchartid:'',
    currentEndTime:'',
    currentStartTime:'',
  },
  methods: {
    sendRequest() {
 //如果是同一個請求就按返回,不需要重復(fù)請求
      if (this.currentMinutehchartid==this.minutehchartid&& this.currentEndTime.getTime()==this.endTime.getTime()&&this.currentStartTime.getTime()==this.startTime.getTime()) {
          return;
       }
       //防止連續(xù)點(diǎn)擊,取消上一次請求
         if (this.source != '') {
            this.source.cancel();
         }
       this.currentMinutehchartid=this.minutehchartid;
       this.currentEndTime=this.endTime;
       this.currentStartTime=this.startTime;
       this.source = this.axios.CancelToken.source(); // 這里初始化source對象
       this.axios({
          method: 'post',
          url: "tideInfo/getTideMinuteListPerHour",
          data: {
                endTime: this.endTime,
                startTime:this.startTime,
                tideStationId:_this.minutehchartid
           },
           cancelToken: _this.source.token,
      })
      .then(res => {
        // 你的邏輯
      })
      .catch(res => {
        // 如果調(diào)用了cancel方法,那么這里的res就是cancel傳入的信息
        // 你的邏輯
           if (this.axios.isCancel(response)) {
                console.log('Request canceled', response.message);
            } else {
               this.$message({
                        type: 'info',
                         message: '服務(wù)器錯誤!'
                });
             }
      })
    },
  }
})

這樣,隨便你怎么瘋狂地點(diǎn)擊,只要上一個請求沒有返回結(jié)果,再次請求的話,就會取消上一個請求,執(zhí)行當(dāng)前請求。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,063評論 25 709
  • 提起蘋果派,好多人都想到了西方人熱衷它的那種氛圍了吧重要時刻,家庭朋友間的聚會也會自己做一塊來分享快樂,酥脆松軟的...
    萊客優(yōu)購烘培閱讀 546評論 0 0

友情鏈接更多精彩內(nèi)容