我正在构建一个vue应用程序,我正在使用axios.我有一个加载图标,我在每次通话之前显示并隐藏在之后.
我只是想知道是否有一种方法可以在全球范围内执行此操作,因此我不必在每次调用时都编写显示/隐藏加载图标?
这是我现在的代码:
context.dispatch('loading', true, {root: true});
axios.post(url,data).then((response) => {
// some code
context.dispatch('loading', false, {root: true});
}).catch(function (error) {
// some code
context.dispatch('loading', false, {root: true});color: 'error'});
});
我在axios docs上看到有“拦截器”,但我不知道它们是处于全球水平还是每次通话.
我也看到了这个帖子的jquery解决方案,不知道如何在vue上实现它:
$('#loading-image').bind('ajaxStart', function(){
$(this).show();
}).bind('ajaxStop', function(){
$(this).hide();
});
解决方法:
我会在根组件的创建生命周期钩子(例如App.vue)中设置Axios interceptors:
created() {
axios.interceptors.request.use((config) => {
// trigger 'loading=true' event here
return config;
}, (error) => {
// trigger 'loading=false' event here
return Promise.reject(error);
});
axios.interceptors.response.use((response) => {
// trigger 'loading=false' event here
return response;
}, (error) => {
// trigger 'loading=false' event here
return Promise.reject(error);
});
}
由于您可能有多个并发Axios请求,每个请求具有不同的响应时间,因此您必须跟踪请求计数以正确管理全局加载状态(每个请求的递增,每个请求解析时递减,并在计数时清除加载状态)达到0):
data() {
return {
refCount: 0,
isLoading: false
}
},
methods: {
setLoading(isLoading) {
if (isLoading) {
this.refCount++;
this.isLoading = true;
} else if (this.refCount > 0) {
this.refCount--;
this.isLoading = (this.refCount > 0);
}
}
}
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!