Vue Router 钩子未在组件中触发,使用 Typescript

shu*_*why 3 javascript typescript vue.js vue-router vue-component

这让我困惑了一段时间。我已经搜索了很多,但仍然不知道为什么路由钩子在组件中不起作用:

1.从RouterView加载组件:

<router-view class="z1" :key="$route.name" />
Run Code Online (Sandbox Code Playgroud)

2. 我已经在main.ts, 和My.vue-- BEFORE 类定义中注册了钩子(以确保注册就在这里):

Component.registerHooks([
    'beforeRouteEnter',
    'beforeRouteLeave',
    'beforeRouteUpdate',
]);
Run Code Online (Sandbox Code Playgroud)

3.钩子甚至在我的路由器配置中工作:

{
    path: '/my',
    name: 'my',
    component: My,
    // beforeEnter: (to: Route, from: Route, next: any): void => {
    //  console.log('It works!’);  // It works here!
    // }
},
Run Code Online (Sandbox Code Playgroud)

4. 但它在我的组件中不起作用:

@Comp()
export default class My extends Vue {
    public beforeRouteEnter (to: Route, from: Route, next: any): void {
        debugger;       // not triggered!
        next((vm: Vue.Component) => {
            debugger;   // not triggered!
            next();
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

那么有人可以帮我吗?

Nik*_*ita 7

应该工作:

@Comp({
  beforeRouteEnter (
    to: Route,
    from: Route,
    next: (to?: RawLocation | false | ((vm: V) => any) | void) => void
  ): void {
       next(vm => {});
  }
})
export default class My extends Vue {}
Run Code Online (Sandbox Code Playgroud)