在项目中会遇到客户要求能够点击按钮中断某个请求,上代码
//that为页面带调用该接口时传的参数
export const xxx接口= (data,that) => {
return http({
cancelToken: new axios.CancelToken(function executor(c) {
that.cancel=c //关键代码,通过传递一个 executor 函数到 CancelToken 的构造函数来创建一个 cancel token,并将参数赋值给接口传过来的参数that
}),
url: 'video/update/newVideo',
method: 'post',
data,
//onUploadProgress,
headers: {
'Content-Type': 'multipart/form-data;charset=UTF-8'
},
});
};
取消请求接口的页面,直接调用即可
if (this.cancel) {
this.cancel('取消了这次请求');
this.cancel=null
};
注意:从 v0.22.0
开始,Axios 支持以 fetch API 方式—— AbortController 取消请求:具体可以看官方文档,这个办法适用于v0.22.0
以下的