在beforeRouteEnter内访问应用程序 [英] Accessing app inside beforeRouteEnter

查看:31
本文介绍了在beforeRouteEnter内访问应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当组件准备由 vue 路由器渲染时,我想在应用根目录中显示一些加载动画.

I'd like to show some loading animation in the app root while a component prepares to be rendered by vue router.

已经找到这个问题,建议使用导航守卫,另一个问题,其中接受的答案显示了如何使用 beforeEach 守卫在 app 中设置变量,显示加载动画.

Already found this question, proposing the use of navigation guards, and another question, where the accepted answer shows how to use the beforeEach guard to set a variable in app, showing a loading animation.

问题是当深度链接到某些路由时,这不起作用(初始 url 包含路由路径,例如someurl#/foo").beforeEach 守卫在那时根本不会被调用.

The problem is that this doesn't work when deep-linking to some route (initial url includes a route path, such as 'someurl#/foo'). The beforeEach guard simply doesn't get called then.

所以我切换到加载组件的 beforeRouteEnter 保护,这也允许我只显示某些组件的加载动画:

So i switched to the loaded component's beforeRouteEnter guard, which would also allow me to show the loading animation for some components only:

应用:

var app = new Vue({
  el: '#app',
  data: { loading: false }
  router: router
});

组件:

var Foo = { 
  template: '<div>bar</div>',
  beforeRouteEnter: function(to, from, next) {
    app.loading = true; // 'app' unavailable when deep-linking
    // do some loading here before calling next()...
    next();
  }
}

但后来我发现当深度链接到组件时,appbeforeRouteEnter 中不可用,因为它在初始化过程的早期被调用.

But then i found that when deep-linking to the component, app isn't available in beforeRouteEnter, as it gets called very early in the initialisation process.

我不想在应用数据声明中将 loading 设置为 true,因为我可能会在某个时候决定深度链接到另一个路由,其组件不需要加载动画.

I don't want to set loading to true inside the app data declaration, as i might decide at some point to deep-link to another route, whose component doesn't need a loading animation.

推荐答案

找到了使用 Vue.nextTick 的解决方法:

Found a workaround using Vue.nextTick:

beforeRouteEnter: function(to, from, next) {
    Vue.nextTick(function(){
      // now app is available
      app.loading = true;
      // some loading to happen here...
      seTimeout(function(){            
        app.loading = false;
        next();  
    }, 1000); 
  })
}

感觉有点老套,所以感谢其他建议.

Feels a little hacky, so would be thankful for other suggestions.

在此处查找此解决方案的演示:https://s.codepen.io/schellmax/debug/aYvXqx/GnrnbVPBXezr#/foo

Find a demo of this solution here: https://s.codepen.io/schellmax/debug/aYvXqx/GnrnbVPBXezr#/foo

这篇关于在beforeRouteEnter内访问应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆