axios的config中提供了一個cancelToken的屬性來取消請求泡挺,在vue-cli中辈讶,使用cancelToken來取消請求。
const CANCEL_TOKEN = axios.CancelToken;
/**
* vue添加原型屬性娄猫,記錄請求信息
*/
Vue.prototype.$httpRequestList = [];
axios({
url: url,
methods: 'POST',
data: options,
cancelToken: new CANCEL_TOKEN(c => { //強行中斷請求要用到的贱除,記錄請求信息
Vue.prototype.$httpRequestList.push(c);
})
}).then(res => {}).catch(err => {
if (err.message == "interrupt") {
console.log('已中斷請求');
return;
}
})
/**
* 在路由切換之前檢測來中斷上個頁面的請求
*/
router.beforeEach((to, from, next) => { //路由切換檢測是否強行中斷生闲,
if(Vue.$httpRequestList.length>0){ //強行中斷時才向下執(zhí)行
Vue.$httpRequestList.forEach(item=>{
item('interrupt');//給個標志,中斷請求
})
}
next();
});
vuex管理
export default createStore({
state: {
httpRequestList: [],
},
mutations: {
addHttpRequestList(state, payload) {
if (payload == 0) {
//強行中斷時才向下執(zhí)行
state.httpRequestList.forEach(item => {
item("interrupt"); //給個標志月幌,中斷請求
});
state.httpRequestList = [];
} else {
state.httpRequestList.push(payload);
}
},
},
actions: {
async removeHttpRequestList(ctx) {
ctx.commit("addHttpRequestList", 0);
},
},
modules: {},
});
/*調用*/
store.dispatch('removeHttpRequestList');
/*請求配置*/
config.cancelToken = new CancelToken(c => {
//強行中斷請求要用到的
store.commit("addHttpRequestList", c);
});