axios取消请求
应用场景:防止用户频繁发送请求,实现发送请求的防抖
官网上描述的使用方法有两种,如下:
- 利用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>
把浏览器网速调慢,疯狂点击按钮,会发现后面点击发送的请求都被取消了,如下图所示
- 使用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>
同样把浏览器网速调慢,疯狂点击按钮,发现后面点击发送的请求也都被取消了,和之前的是一样的。