濮阳开公司怎么找客户,在运营中seo是什么意思,wordpress 修改字体大小和文章行距的方法,免费网站空间申请前言
最近开发过程中#xff0c;总是遇到想把正在请求的axios接口取消#xff0c;这种情况有很多应用场景#xff0c;举几个例子#xff1a;
弹窗中接口请求返回图片#xff0c;用于前端展示#xff0c;接口还没返回数据#xff0c;此时关闭弹窗#xff0c;需要中断接…前言
最近开发过程中总是遇到想把正在请求的axios接口取消这种情况有很多应用场景举几个例子
弹窗中接口请求返回图片用于前端展示接口还没返回数据此时关闭弹窗需要中断接口请求tab标签页根据后端返回数据依次渲染频繁切换标签需要中断接口请求for循环中请求接口遇到跳出循环情况也需要中断接口请求跳转路由离开页面时可能也需要中断接口请求
下面就是根据以上问题找到的解决方案
正文
因为axios不同版本取消请求是不同的目前最新的 axios 的取消请求api推荐使用 AbortController 旧版本的 CancelToken 在 v0.22.0 后弃用截止到此片文章发表npm上的axios版本号已经更新到v1.5.1但是相信有一些项目的版本还是v0.x.x的所以下面分别介绍两种取消方式大家根据自己项目axios版本号自行查看 v0.22.0 CancelToken
get请求
el-button typeprimary clicksendGet()发送get请求/el-button
el-button typedanger clickcancel()取消请求/el-buttonimport {ref,onMounted,onUnmounted} from vue
import axios from axios;let source:any null;
const sendGet (){//可以理解为给定每个接口一个标识source axios.CancelToken.source();axios.get(请求url,{cancelToken: source.token}).then(res {console.log(get请求,res)}).catch(err {if (axios.isCancel(err)) {console.log(请求取消, err);} else {console.log(其他错误, err)}});
}const cancel (){source source.cancel(手动调用 source.cancel方法手动取消请求);
}post请求
el-button typesuccess clicksendPost()发送post请求/el-button
el-button typedanger clickcancel()取消请求/el-buttonimport {ref,onMounted,onUnmounted} from vue
import axios from axios;let source:any null;
const sendPost (){source axios.CancelToken.source();axios.post(请求url,{},//传参没有也必须加上{}{cancelToken: source.token}).then((res) {console.log(post请求,res)}).catch(err {if (axios.isCancel(err)) {console.log(请求取消, err);} else {console.log(其他错误, err)}})
}const cancel (){source source.cancel(手动调用 source.cancel方法手动取消请求);
}v1.5.1 AbortController
使用fetch() 是一个全局方法它的请求是基于 Promise 的 method - 请求方法默认GET signal - 用于取消 fetch
el-button typeprimary clicksendNewGet()发送get请求/el-button
el-button typedanger clickcancelController()取消新版请求/el-buttonimport {ref,onMounted,onUnmounted} from vue
import axios from axios;let controller:any null;const sendNewGet (){controller new AbortController(); // 新建一个AbortController实例fetch(请求url,{signal: controller.signal // signal是AbortController实例的属性}).then(res {console.log(新版get请求,res)//处理返回数据res.json().then(res1 {console.log(res1)})}).catch(err {console.log(err)});
}const cancelController (){controller controller.abort();//调用abort方法
}