cancelToken来取消请求(axios中断请求cancelToken)
用户投稿
•
•
阅读 311
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);
});
随机文章
站长导航搜素引擎算法
关键词排名优化
SEO小小课堂网
SEO教程
站长导航
友情链接交换
搜素引擎算法
百度搜索“网赚联盟”即可找到本站,微信搜索“小小课堂网”关注小小课堂网公众号。网赚联盟( wangzhuan.org.cn )欢迎用户投稿,发布者:用户投稿,文章版权归作者所有,投稿文章不代表网赚联盟立场,中二少年发布为网赚联盟原创文章,转载请注明出处:https://wangzhuan.org.cn/126706.html

微信扫一扫
支付宝扫一扫