在显示加载屏幕 VueJS 之前等待一段时间

Wait for some time before showing loading screen VueJS

VueJS 中,我将每条路线上的加载程序显示为:

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

但是,如果服务器加载页面的时间少于一秒,那么显示此请求的加载器仅一秒钟就显​​得很奇怪。

我想等待一段时间,只说 2 秒或 3 秒,毕竟,如果页面尚未加载,则显示加载程序,否则不显示。因此,为此,我将 setTimeout 设为:

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

现在加载器总是显示永远不会运行然后我也尝试将 next() 语句移动到 setTimeout 但是页面首先等待 500 mili-sec 然后加载器出现然后突然隐藏并加载页面。

我想以更好的方式制作它,有什么建议吗?

关于你的问题。截至目前,您仅将提交 'loading' 突变延迟 500 毫秒。要回答您的问题,您应该这样做:

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

这将延迟提交 store.commit('loading', false); 500 毫秒。问题是你真的想错误地延迟组件的加载吗?为什么不在那种情况下使用转换?

以下是如何延迟加载下一条路线的示例 https://codesandbox.io/s/vue-highcharts-demo-nn3uv

我认为您不了解 Vue Router Navigation Guards。根据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.

简而言之,只需在 beforeEach 中显示加载程序即可:

store.commit('loading', true);

然后将其隐藏在 afterEach 中:

store.commit('loading', false);

就是这样。

Don't add setTimeout in afterEach.

希望对您有所帮助。