切换路由时取消全部或者部分axios请求,并将一些从不需要取消的加入白名单
1. axios拦截器进行配置,除了白名单中的接口,统统保存到全局变量canCancelAxios中
window.canCancelAxios = [];
// http request 拦截器
axios.interceptors.request.use(
config => {
let whiteList = ['/test1', '/test2']; // 白名单接口
if (config.url && whiteList.every(item => !config.url.includes(item))) {
config.cancelToken = new axios.CancelToken(function (c) { window.canCancelAxios.push({ key: config.key || "", cancel: c }) });
}
return config;
},
err => {
return Promise.reject(err);
}
)
2. 定义一个取消取消axios的方法
/**
* 取消axios请求
* @param cellArr 要取消的接口;如果不传参,则取消canCancelAxios保存的所有接口
*/
export function cancelAxios(cellArr = []) {
if (cellArr.length > 0) {
cellArr.forEach(val => {
for (let i = 0; i < window.canCancelAxios.length; i++) {
if (window.canCancelAxios[i].key === val) {
window.canCancelAxios[i].cancel();
window.canCancelAxios.splice(i, 1);
i--;
}
}
})
} else {
for (let i = 0; i < window.canCancelAxios.length; i++) {
window.canCancelAxios[i].cancel();
window.canCancelAxios.splice(i, 1);
i--;
}
}
}
3. 路由配置中,路由切换时,取消axios请求
import cancelAxios from "***";
router.beforeEach((to, from, next) => {
cancelAxios();
// 进行其他业务操作
})
4. 特殊情况下(比如切换tab页时),可能需要取消特定某些axios
import cancelAxios from "***";
cancelAxios(["axios1", "axios2"]);
注意
// 这里取消特定的axios是根据axios拦截器中config.key来识别接口的,所以接口请求时要配置key参数,不然不能正确取消;
// 比如上面要取消的["axios1", "axios2"]
test1: () => Axios.get(`/path1`, { key: "axios1" }),
test2: () => Axios.get(`/path2`, { key: "axios2" })