I have a lot of AJAX requests in my app and I'd like to show loading icon for every request and remove it when response is received. I am using axios for these calls, so I created a simple plugin class and added custom axios interceptors.
const MyGlobalVariables= {
install(Vue, options) {
Vue.load_mask = true;
MyGlobalVariables.getLoadMask = function() {
return Vue.load_mask;
},
MyGlobalVariables.setLoadMask = function(val) {
Vue.load_mask = val;
}
}
};
export default MyGlobalVariables;
Then the interceptors
// Add a request interceptor
window.axios.interceptors.request.use(function (config) {
// Do something before request is sent
MyGlobalVariables.setLoadMask(true);
console.log(MyGlobalVariables.getLoadMask());
return config;
}, function (error) {
MyGlobalVariables.setLoadMask(false);
console.log(MyGlobalVariables.getLoadMask());
// Do something with request error
return Promise.reject(error);
});
// Add a response interceptor
window.axios.interceptors.response.use(function (response) {
// control the load mask on AJAX calls
MyGlobalVariables.setLoadMask(false);
console.log(MyGlobalVariables.getLoadMask());
return response;
}, function (error) {
MyGlobalVariables.setLoadMask(false);
console.log(MyGlobalVariables.getLoadMask());
// Do something with response error
return Promise.reject(error);
});
So that part works fine. my global variable is toggled true/false at the appropriate time. What I am having difficulty with is how do I set a variable on my main template that actually toggles it?
In my example, I have an inline-template that is the root of my entire project.
<home :user="user" inline-template>
// Bunch of content here
<div v-if="shouldShowLoadMask" class='lmask'></div>
</home>
Then in my home.js file:
import MyGlobalVariables from "./extras/my-global";
Vue.component('home', {
props: ['user'],
computed: {
shouldShowLoadMask() {
console.log('show load mask? ' + MyGlobalVariables.getLoadMask());
return MyGlobalVariables.getLoadMask();
},
}
The issue is shouldShowLoadMask is only fired once at the beginning of the app. So I need to watch (or something similar) on the plugin variable. But how? I saw an example where someone referenced Vuex, but I am not using it in my app.
TL;DR: How do I monitor a global plugin variable so I can toggle an element on and off with v-if ?