axios取消请求

axios取消请求

应用场景:防止用户频繁发送请求,实现发送请求的防抖

官网上描述的使用方法有两种,如下:

  1. 利用CancelToken构造函数
<template>
  <div class="hello">
    <button @click="sendReq">发送请求</button>
  </div>
</template>

<script>
import axios from 'axios'
export default {
  name: 'HelloWorld',
  data () {
    return {
      sourse: null
    }
  },
  methods: {
    sendReq () {
      const CancelToken = axios.CancelToken
      this.source && this.source.cancel('请求已取消')
      this.source = CancelToken.source()
      // get请求cancelToken定义在第二个参数中
      axios
        .get('http://localhost:3000/list?num=10', {
          cancelToken: this.source.token
        })
        .then(res => {
          console.log(res)
        })
        .catch(function (thrown) {
          if (axios.isCancel(thrown)) {
            console.log('Request canceled', thrown.message)
          } else {
            // handle error
          }
        })

      // post请求cancelToken定义在第三个参数中
      // axios.post(
      //   'http://localhost:3000/list?num=10',
      //   {
      //     name: 'new name'
      //   },
      //   {
      //     cancelToken: this.source.token
      //   }
      // )
    }
  }
}
</script>

把浏览器网速调慢,疯狂点击按钮,会发现后面点击发送的请求都被取消了,如下图所示
在这里插入图片描述

  1. 使用executor
<template>
  <div class="hello">
    <button @click="sendReq">发送请求</button>
  </div>
</template>

<script>
import axios from 'axios'
export default {
  name: 'HelloWorld',
  data () {
    return {
      cancel: null
    }
  },
  methods: {
    sendReq () {
      const CancelToken = axios.CancelToken
      this.cancel && this.cancel('请求已被取消')
      const that = this
      
      axios.get('https://autumnfish.cn/api/joke/list?num=10', {
        cancelToken: new CancelToken(function executor (c) {
          // An executor function receives a cancel function as a parameter
          that.cancel = c
        })
      })
    }
  }
}
</script>

同样把浏览器网速调慢,疯狂点击按钮,发现后面点击发送的请求也都被取消了,和之前的是一样的。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值