Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
140
rated 0 times [  146] [ 6]  / answers: 1 / hits: 52786  / 6 Years ago, fri, june 8, 2018, 12:00:00

I'm currently building a vue app and Im using axios. I have a loading icon which i show before making each call and hide after.



Im just wondering if there is a way to do this globally so I dont have to write the show/hide loading icon on every call?



This is the code I have right now:



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'});
});


I have seen on the axios docs there are interceptors but II dont know if they are at a global level or on each call.



I also saw this post for a jquery solution, not sure how to implement it on vue though:



$('#loading-image').bind('ajaxStart', function(){
$(this).show();
}).bind('ajaxStop', function(){
$(this).hide();
});

More From » vue.js

 Answers
18

I would setup Axios interceptors in the root component's created lifecycle hook (e.g. App.vue):



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);
});
}


Since you could have multiple concurrent Axios requests, each with different response times, you'd have to track the request count to properly manage the global loading state (increment on each request, decrement when each request resolves, and clear the loading state when count reaches 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);
}
}
}


demo


[#54243] Tuesday, June 5, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
austonjuancarlosb

Total Points: 238
Total Questions: 89
Total Answers: 99

Location: Chad
Member since Mon, Dec 5, 2022
1 Year ago
;