"next" 在 beforeRouteUpdate 中未定义

"next" undefined in beforeRouteUpdate

@Component({
  mixins: [template],
  components: {
    Sidebar
  }
})
export default class AppContentLayout extends Vue {

  @Prop({default: 'AppContent'})
  heading: string;

  @Watch('$route')
  beforeRouteUpdate (to: Object, from: Object, next: Function) {
    // react to route changes...
    // don't forget to call next()
    Logger.log(to)
    Logger.log(from)
    next();
  }
}

基于 docs, beforeRouteUpdate should receive to, from and next. However, for me next is always undefined, whether I use the watch option from a property decorator 或当我将其添加到 @component 中的 mixins 时。两者都在调用挂钩时工作,但下一个总是 undefined。我想也许 next 仅在通过时才定义,但文档状态:

Make sure to always call the next function, otherwise the hook will never be resolved.

这就是我假设它也始终存在的原因。我想如果它只在通过时存在,一个简单的

if(isFunction(next)) next()

所以我真正要问的是:next 只有在明确通过后才可用吗?

我不是 Vue 专家,但我想知道你是否在这里混合了两种机制......你似乎同时在做手表和路由更新之前都与同一个方法有关。

Watch 没有得到 next 参数,而 beforeRouteUpdate 有,所以我想缺少的参数与那个 Watch 属性相关,只用 [=15] 触发方法=] 和 from.

观看

const User = {
  template: '...',
  watch: {
    '$route' (to, from) {
      // react to route changes...
    }
  }
}

路由更新前

const User = {
  template: '...',
  beforeRouteUpdate (to, from, next) {
    // react to route changes...
    // don't forget to call next()
  }
}

好的,文档是这么说的

To react to params changes in the same component, you can simply watch the $route object:

Or, use the beforeRouteUpdate guard introduced in 2.2:

当您使用打字稿注释时,您必须命名您挂接的回调。不幸的是,我只是碰巧称它为 beforeRouteUpdate,因为我也在路由器文档中查找了它。现在我以为它会调用 beforeRouteUpdate,但它没有,它只是调用了我这样命名的回调。

因此,将回调重命名为 onRouteChange 更有意义 "did the trick"

完全不确定答案实际指的是什么。但是我 运行 遇到了同样的问题,对我来说 b/c 我注册的钩子比我使用的要多,我认为这无关紧要。一旦我只注册了我定义的那个,它就按预期工作了。

即如果组件只提供 beforeRouteUpdate,这将不起作用:

Component.registerHooks([
    'beforeRouteEnter',
    'beforeRouteLeave',
    'beforeRouteUpdate'
]);

但这将:

Component.registerHooks([
    'beforeRouteUpdate'
]);