简体   繁体   中英

Wait for some time before showing loading screen VueJS

In VueJS , I am showing the loader on each route as:

router.beforeEach((to, from, next) => {
  store.commit('loading', true);
  next();
})

But if server loads the page in less than one second then it looks weird to show loader for this request, for just one sec.

What I want to wait for some time let just say 2sec or maybe 3sec and after all, if the page is not loaded yet then show loader otherwise not. So for this, I put setTimeout as:

router.beforeEach((to, from, next) => {
  setTimeout(() => {
    store.commit('loading', true);
  }, 500);
  next();
})

Now the loader is always shown never goes then I also tried to move next() statement into setTimeout but then the page first waits for 500 mili-sec then the loader shows up and then hides suddenly and page loads.

I want to make it in a better way, any suggestions?

so about your question. As of now you're only delaying commiting 'loading' mutation by 500ms. To answer your question you should do something like that:

router.beforeEach((to, from, next) => {
  store.commit('loading', true);
   setTimeout(() => {
    store.commit('loading', false);
   }, 500);
   next();
})

That will delay commiting store.commit('loading', false); by 500ms. The question is do you really want to falsely delay loading of a component. Why not use transitions in that case ?

Here is example how loading next route is delayed https://codesandbox.io/s/vue-highcharts-demo-nn3uv

I think you are not understanding the Vue Router Navigation Guards. According to Vue Router Docs :

Global before guards are called in creation order, whenever a navigation is triggered. Guards may be resolved asynchronously, and the navigation is considered pending before all hooks have been resolved.

In simple words, just show the loader in beforeEach as you are doing:

store.commit('loading', true);

And just hide it in afterEach as:

store.commit('loading', false);

That's it.

Don't add setTimeout in afterEach .

Hope it will help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM