Home  >  Article  >  Web Front-end  >  How to implement vue+axios interrupt request when switching pages

How to implement vue+axios interrupt request when switching pages

php中世界最好的语言
php中世界最好的语言Original
2018-04-12 11:22:313114browse

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;
};
Connect to axios and add cancelToken data in the POST method. In the else above, interrupt requests and request errors will go there, so use a msg to identify it (because

Interface

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 of

routingswitch.beforeEach, cancel is the method of interrupting, which is taken out from the cancelToken of the post

Vue.prototype.cancelAjax = function(){ //切换页面强行中断请求 router.beforeEach中用到 
 if(cancel){ 
  cancel(cancelAjaxText); 
 } 
}
rrree

Calling post

router.beforeEach((to, from, next) => { 
<span style="white-space:pre;"> </span>Vue.prototype.cancelAjax()  
 next(); 
});
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Detailed explanation of the use of js data types


Detailed explanation of the steps for using deep and shallow copies of JS


The 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn