vueaxios在页⾯切换时中断请求⽅法ajax
如下所⽰:
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 来区别
发送ajax请求的步骤
ssage == cancelAjaxText){
return {status : false,msg:cancelAjaxText}
}else{
this.$confirm('登录过时,是否重新登录', '提⽰', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
window.location.href = Vue.prototype.url_head + '/';
}).catch(() => {
});
}
})
return ajax;
};
接⼊ axios ,在POST⽅法⾥加⼊ cancelToken 数据,在上⾯else中,中断请求和请求出错都会⾛那⾥,所以⽤⼀个msg来识别(因为接⼝返回中也有⼀个msg,统⼀⼀下);
以下是中断请求的⽅法,放在路由切换的监听 router.beforeEach 中,cancel 是中断的⽅法,在post 的 cancelToken ⾥⾯拿出来的
Vue.prototype.cancelAjax = function(){ //切换页⾯强⾏中断请求 router.beforeEach中⽤到
if(cancel){
cancel(cancelAjaxText);
}
}
router.beforeEach((to, from, next) => {
<span > </span>Vue.prototype.cancelAjax()
next();
});
调⽤post
<span >  </span>this.post(this.ajaxUrl + 'getCrTree',{
devAddr : this.changeData.devAddr,
innerId : this.changeData.innerId,
}).then(ret=>{
if(ret.status){
}else{
this.msg(ret.msg);
}
})
以上这篇vue axios 在页⾯切换时中断请求⽅法 ajax就是⼩编分享给⼤家的全部内容了,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。