axios的config中提供了一个cancelToken的属性来取消请求,在vue-cli中,使用cancelToken来取消请求。
const CANCEL_TOKEN = axios.CancelToken;
/**
* vue添加原型属性,记录请求信息
*/
Vue.prototype.$httpRequestList = [];
axios({
url: url,
methods: 'POST',
data: options,
cancelToken: new CANCEL_TOKEN(c => { //强行中断请求要用到的,记录请求信息
Vue.prototype.$httpRequestList.push(c);
})
}).then(res => {}).catch(err => {
if (err.message == "interrupt") {
console.log('已中断请求');
return;
}
})
/**
* 在路由切换之前检测来中断上个页面的请求
*/
router.beforeEach((to, from, next) => { //路由切换检测是否强行中断,
if(Vue.$httpRequestList.length>0){ //强行中断时才向下执行
Vue.$httpRequestList.forEach(item=>{
item('interrupt');//给个标志,中断请求
})
}
next();
});
网友评论