axios中断请求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){ //强行中断时才向下执行
Vue.$httpRequestList.forEach(item=>{
item('interrupt');//给个标志,中断请求
})
}
next();
});
vuex管理
export default createStore({
state: {
httpRequestList: [],
},
mutations: {
addHttpRequestList(state, payload) {
if (payload == 0) {
//强行中断时才向下执行
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);
});
本站文章除注明转载外,均为原创文章。转载请注明:文章转载自:
葱爆GIS—刘博方GIS博客(
https://liubf.com )