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

以上就完成了

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值