Below I will share with you an article on how vue axios interrupts the request method ajax when switching pages. It has a good reference value and I hope it will be helpful to everyone.
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, in the above else, interrupt the request and request If there is an error, it will go there, so use a msg to identify it (because there is also a msg in the interface return, unify it);
The following is the method of interrupting the request, which is placed in the listening router.beforeEach of the routing switch. , cancel is the interrupt method, take out the cancelToken of the post
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(); });
Call the post
<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); } })
The above is what I compiled For everyone, I hope it will be helpful to everyone in the future.
Related articles:
setTimeout time is set to 0 Detailed analysis
JS implementation of collection deduplication, intersection, union, difference Set function example
Organization of data-[*] attributes in Bootstrap
The above is the detailed content of In Vue, axios is used to implement the interrupt request method when switching pages.. For more information, please follow other related articles on the PHP Chinese website!