项目中遇到个问题,客户端要等服务端操作3到4秒后才能返回结果,这时候用户退出页面ajax请求还在进行,会影响性能。
axios中提供了两种方式解决中断ajax问题,这里我就说我用的这种。
在main.js中加入以下代码;
Vue.prototype.$http= axios;
const CancelToken = axios.CancelToken;
let cancel;
Vue.prototype.post = function(url,data,loading){ //制定post方法
var ajax = Vue.prototype.$http({
method: 'post',
url:url,
data: data,
cancelToken: new CancelToken(c => { //强行中断
cancel = c
})
}).then(res =>res) //请求成功后的代码
.catch(error=>{ //中断请求和请求出错的处理
if(error.message == "interrupt"){ //判断是中断请求还是错误
console.log('已中断请求')
return;
}else{ //连接服务器请求错误的处理方式
Toast({
message: '请检查网络连接',
position: 'bottom',
duration: 1300
});
}
})
return ajax;
};
router.beforeEach((to, from, next) => { //路由切换检测是否强行中断,
if(cancel){ //强行中断时才向下执行
cancel('interrupt'); //给个标志,中断请求
}
next();
});
页面中调用,不需要catch了。
this.post(Url,{
}).then(res=>{
if(ret.data.code==200){
}else{
}
})
如果操作成功的话,应该是这样的