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="../js/axios.min.js"></script>
</head>
<body>
<button class="btn">请求按钮</button>
<button class="btn_cancel">取消按钮</button>
<script>
const btn = document.querySelector('.btn')
const btn_cancel = document.querySelector('.btn_cancel')
let cancel = null;
btn.addEventListener('click', e => {
axios({
method: 'get',
url: 'http://localhost:3000/posts',
//取消请求配置,c是一个函数
cancelToken: new axios.CancelToken(c => {
cancel = c
})
}).then(resp => {
console.log(resp)
}).catch(err => {
console.log(err)
})
})
//取消请求,执行cancel函数即可
btn_cancel.addEventListener('click', e => {
cancel();
})
</script>
</body>
</html>
2 防抖
放置用户暴力点击,每次都会请求数据;

<!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="../js/axios.min.js"></script>
</head>
<body>
<button class="btn">请求按钮</button>
<script>
const btn = document.querySelector('.btn')
let cancel = null;
btn.addEventListener('click', e => {
//当请求还未完成,canael不为null,若此时快速再次点击,就会取消上次请求
if (cancel !== null) {
cancel()
}
//取消上次请求之后再次请求数据
axios({
method: 'get',
url: 'http://localhost:3000/posts',
cancelToken: new axios.CancelToken((c) => {
cancel = c
})
}).then(resp => {
console.log(resp)
cancel = null
})
})
</script>
</body>
</html>
网友评论