This time I will show you how to implement vue axios to interrupt the request when switching pages. What are the things to pay attention to when implementing vue axios to interrupt the request when switching pages? The following is a practical case, let's take a look. .
is as follows: Vue.prototype.$ajax=axios;
const CancelToken = axios.CancelToken;
let cancel;
let cancelAjaxText = '中断成功';
Vue.prototype.post = function(url,data,loading){
var ajax = Vue.prototype.$ajax({
method: 'post',
url:url,
data: data,
cancelToken: new CancelToken(c => { //强行中断请求要用到的
cancel = c
})
}).then(res =>res.data,res=>{ //中断请求和请求出错都会走这里,我这里用 cancelAjaxText 来区别
if(res.message == cancelAjaxText){
return {status : false,msg:cancelAjaxText}
}else{
this.$confirm('登录过时,是否重新登录', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
window.location.href = Vue.prototype.url_head + '/';
}).catch(() => {
});
}
})
return ajax;
};
also has a msg in the return, unify it) ;
The following is the method of interrupting the request, which is placed in the listening router ofroutingswitch.beforeEach, cancel is the method of interrupting, which is taken out from the cancelToken of the postVue.prototype.cancelAjax = function(){ //切换页面强行中断请求 router.beforeEach中用到
if(cancel){
cancel(cancelAjaxText);
}
}
Calling post router.beforeEach((to, from, next) => {
<span style="white-space:pre;"> </span>Vue.prototype.cancelAjax()
next();
});
Recommended reading:
Detailed explanation of the use of js data typesDetailed explanation of the steps for using deep and shallow copies of JSThe above is the detailed content of How to implement vue+axios interrupt request when switching pages. For more information, please follow other related articles on the PHP Chinese website!