You have already accepted my other answer, but I think the code can be improved significantly, as explained below:
It is generally recommended not to mix jQuery
with Vue.js
, as both modify DOM:
Vue.js
has a very strong hold on the DOM, for its model-view bindings, using its Reactivity System
jQuery
may modify using class
or id
selectors, if you use it for some quick-fix solution somewhere.
You will end up spending a lot of time debugging frontend issues, which takes focus away from the business requirements. Also, Vue.js
already requires modern browsers, so technically jQuery
is not doing much for browser compatibility - its primary goal.
So if you are open to leaving jQuery
behind, here is another method:
getDelayedData() {
// Create a new Promise and resolve after 2 seconds
var myTimerPromise = new Promise((resolve, reject) => {
setTimeout(() => {
// callback function for timer, gets called after the time-delay
// Your timer is done now. Print a line for debugging and resolve myTimerPromise
console.log("2 seconds up, resolving myTimerPromise")
resolve();
}, 2000); // This promise will be resolved in 2000 milli-seconds
});
// Start displaying ajax spinner before fetching data
this.displaySpinner = true;
// Fetch data now, within Promise.all()
Promise.all([myTimerPromise, this.getPosts(), this.getSliders()]).then( () => {
// Hide the spinner now. AJAX requests are complete, and it has taken at least 2 seconds.
this.displaySpinner = false;
console.log("Data fetched for sliders and posts");
});
}
The above code also requires you to have this.displaySpinner
, which activates or deactivates your ajax spinner. Or you may have some other way of doing it.
And you still need to return this.$http.get(..)
from your getPosts
and getSliders
methods.
Note: I haven't tested the above code, you need to debug if required. It should work, based on my understanding of Promise.all() as given in this reference doc: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
Once it starts working, you can simplify myTimerPromise
as follows:
getDelayedData() {
// Create a new Promise and resolve after 2 seconds
var myTimerPromise = new Promise((resolve, reject) => {
setTimeout(resolve, 2000); // "resolve" is already a function, no need for another anonymous function here
});
// and do the other stuff here...
}
I would prefer this method, as it avoids jQuery
. Then my Vue.js
app can be as small as 30 KB gzipped, whereas if I bundle jQuery
along, it can go well over 100 KB. It is just a personal choice :-)