如下所示:
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 => { //強(qiáng)行中斷請求要用到的 cancel = c }) }).then(res =>res.data,res=>{ //中斷請求和請求出錯都會走這里,我這里用 cancelAjaxText 來區(qū)別 if(res.message == cancelAjaxText){ return {status : false,msg:cancelAjaxText} }else{ this.$confirm('登錄過時(shí),是否重新登錄', '提示', { confirmButtonText: '確定', cancelButtonText: '取消', type: 'warning' }).then(() => { window.location.href = Vue.prototype.url_head + '/'; }).catch(() => { }); } }) return ajax;};
接入 axios ,在POST方法里加入 cancelToken 數(shù)據(jù),在上面else中,中斷請求和請求出錯都會走那里,所以用一個(gè)msg來識別(因?yàn)榻涌诜祷刂幸灿幸粋€(gè)msg,統(tǒng)一一下);
以下是 中斷請求的方法,放在 路由切換的監(jiān)聽 router.beforeEach 中 ,cancel 是中斷的方法,在post 的 cancelToken 里面拿出來的
Vue.prototype.cancelAjax = function(){ //切換頁面強(qiáng)行中斷請求 router.beforeEach中用到 if(cancel){ cancel(cancelAjaxText); } }
router.beforeEach((to, from, next) => { <span style="white-space:pre;"> </span>Vue.prototype.cancelAjax() next(); });
調(diào)用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); } })
以上這篇vue axios 在頁面切換時(shí)中斷請求方法 ajax就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持武林網(wǎng)。
新聞熱點(diǎn)
疑難解答