Vue使用axios,終止多次請求方式,防抖

Vue使用axios,終止多次請求方式,防抖

三種防抖策略:

  1. 定時器;
  2. abort();
  3. axios自帶撤銷請求

這裏只說第三種的使用步驟~
1.首先在methods中添加方法:

  methods: {
    cancelRequest(){
        if(typeof this.source ==='function'){
            this.source('終止請求')
        }
    }
  }

2.在請求開始前緩存this,並且調用上面方法,取消請求

	var that = this;
	this.cancelRequest();

3.請求時給axios傳入第二個參數;

	this.axios.get('請求路徑', {
	    cancelToken: new this.axios.CancelToken(function(c) {
	      that.source = c;
	    })
	  }).then((res)=>{
	    //正常響應需要做的處理
	  }).catch((err) => {
	    if (that.axios.isCancel(err)) {
	      console.log('Rquest canceled', err.message); //請求如果被取消,這裏是返回取消的message
	    } else {
	      //handle error
	      console.log(err);
	    }
	  }) 

以上就完成了

發佈了4 篇原創文章 · 獲贊 3 · 訪問量 695
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章