1.代码示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>
</head>
<body>
<button>点击获取数据</button>
<script>
const btn0 = document.getElementsByTagName("button")[0];
let cancel = null;
btn0.addEventListener("click", function () {
if (cancel !== null) {
cancel();
}
axios({
method: "GET",
url: "http://localhost:3000/posts",
cancelToken: new axios.CancelToken(function (c) {
cancel = c;
}),
}).then((response) => {
console.log(response);
cancel = null;
});
});
</script>
</body>
</html>
2.示例代码讲解
axios({
method: "GET",
url: "http://localhost:3000/posts",
cancelToken: new axios.CancelToken(function (c) {
cancel = c;
}),
- axios的cancelToken属性为一个axios的CancelToken对象。该对象的构造参数为一个函数,这个函数的参数也是一个函数。
- 将这个参数函数赋值给一个变量,使用这个函数就可以取消axios请求
3.运行结果
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/94330e739a4b9a29e39f7a893e3e3ef4.png)