vue.js - 在 beforeRouteEnter 中访问应用程序

标签 vue.js vue-router

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

已找到this question ,建议使用导航守卫,以及another question ,其中接受的答案显示如何使用 beforeEach 守卫在 app 中设置变量,显示加载动画。

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

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

应用:

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 中不可用,因为它在初始化过程的早期被调用。

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

最佳答案

我相信,您的解决方案是正确的。但是,我建议改用 next() 函数。如 vue-router 文档中所写。 https://router.vuejs.org/en/advanced/navigation-guards.html

The beforeRouteEnter guard does NOT have access to this, because the guard is called before the navigation is confirmed, thus the new entering component has not even been created yet.

However, you can access the instance by passing a callback to next. The callback will be called when the navigation is confirmed, and the component instance will be passed to the callback as the argument:

beforeRouteEnter (to, from, next) {
  next(vm => {
    vm.$root.loading = true;
  })
}

关于vue.js - 在 beforeRouteEnter 中访问应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49276470/

相关文章:

javascript - 如何在 VueFire 中创建动态引用?

javascript - 如何在 Bootstrap 选项卡中创建多个 Vue 组件?

javascript - 从 vue.js 中的子发射传递时值未定义

javascript - 为什么index-of在vuejs中不能正常工作?

vue.js - 找不到模块 : Error: Can't resolve in vuejs

vue.js - Tailwind 不适用于带有 Sass 的 vue 4.3.1

javascript - Firebase beforeeach() 触发很多次(Vue 应用程序)

javascript - View |如何将Web端口号更改为80?

javascript - Vuejs 将隐藏输入的值设置为路由参数

javascript - 错误: not a function (on mounted)