Home >Web Front-end >JS Tutorial >How to interrupt the request when switching vue axios pages
This time I will show you how to interrupt the request when switching the vue axios page. What are the precautions for interrupting the request when switching the vue axios page. 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, add cancelToken data in the POST method, and interrupt in the else above Requests and request errors will go there, so use a msg to identify them (because there is also a msg in the interface return, unify it);
The following is the method to interrupt the request, put In the listening router.beforeEach of the routing switch, cancel is the interrupt method. The
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(); });
taken out of the cancelToken of the post is called.
#<span style="white-space:pre;"> </span>this.post(this.ajaxUrl + 'getCrTree',{ devAddr : this.changeData.devAddr, innerId : this.changeData.innerId, }).then(ret=>{ if(ret.status){ }else{ this.msg(ret.msg); } })
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to the php Chinese website Other related articles!
Recommended reading:
Detailed explanation of the use of deep and shallow copies of JS
The difference between method and computed in Vue
The above is the detailed content of How to interrupt the request when switching vue axios pages. For more information, please follow other related articles on the PHP Chinese website!