首頁  >  文章  >  web前端  >  vue中透過axios實作在頁面切換時中斷請求方法

vue中透過axios實作在頁面切換時中斷請求方法

亚连
亚连原創
2018-06-01 11:26:312124瀏覽

下面我就為大家分享一篇vue axios 在頁面切換時中斷請求方法 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 来区别
	  	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;
};

接入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 style="white-space:pre;"> </span>Vue.prototype.cancelAjax()  
 next(); 
});

呼叫post

<span style="white-space:pre;">   </span>this.post(this.ajaxUrl + &#39;getCrTree&#39;,{ 
    devAddr : this.changeData.devAddr, 
    innerId : this.changeData.innerId, 
   }).then(ret=>{ 
    if(ret.status){ 
      
    }else{ 
     this.msg(ret.msg); 
    } 
   })

上面是我整理給大家的,希望今後對大家有幫助。

相關文章:

setTimeout時間設定為0詳細解析

#JS實作的集合去重,交集,並集,差集功能範例

Bootstrap 中data-[*] 屬性的整理

以上是vue中透過axios實作在頁面切換時中斷請求方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn