vue axios 在頁面切換時中斷請求方法 ajax
更新時間:2018年03月05日 16:47:59 作者:qq_25186543
下面小編就為大家分享一篇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 來區(qū)別
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 數(shù)據(jù),在上面else中,中斷請求和請求出錯都會走那里,所以用一個msg來識別(因為接口返回中也有一個msg,統(tǒng)一一下);
以下是 中斷請求的方法,放在 路由切換的監(jiān)聽 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();
});
調(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 在頁面切換時中斷請求方法 ajax就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Vue實現(xiàn)側(cè)邊導航欄于Tab頁關聯(lián)的示例代碼
本文主要介紹了Vue實現(xiàn)側(cè)邊導航欄于Tab頁關聯(lián)的示例代碼,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-11-11
基于webpack4+vue-cli3項目實現(xiàn)換膚功能
這篇文章主要介紹了基于webpack4+vue-cli3項目的換膚功能,文中是通過scss+style-loader/useable做換膚功能,本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2019-07-07

