首页 > 解决方案 > Vue Router 钩子未在组件中触发,使用 Typescript

问题描述

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

1、从RouterView加载组件:

<router-view class="z1" :key="$route.name" />

2. 我已经在类定义之前注册了钩子main.ts,并且也在My.vue-- BEFORE 中注册了(以确保注册就在此处):

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

3. 这个钩子甚至可以在我的路由器配置中使用:

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

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();
        });
    }
}

那么有人可以帮我吗?

标签: javascripttypescriptvue.jsvue-componentvue-router

解决方案


应该工作:

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

推荐阅读