【问题标题】:Vue Router hooks not triggered in component, using TypescriptVue Router 钩子未在组件中触发,使用 Typescript
【发布时间】:2019-11-16 00:14:21
【问题描述】:

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

1.从RouterView加载组件:

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

2。我已经在main.tsMy.vue 中注册了钩子——在类定义之前(以确保注册就在此处):

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

那么有人可以帮我解决这个问题吗?

【问题讨论】:

    标签: javascript typescript vue.js vue-component vue-router


    【解决方案1】:

    应该可以工作:

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

    【讨论】:

    • @Component 装饰器接受带有 vue 路由器钩子的对象
    • 我不知道为什么,但打字解决了它
    猜你喜欢
    • 2017-05-30
    • 2022-01-07
    • 2018-04-22
    • 2016-11-09
    • 2022-10-16
    • 2020-12-22
    • 1970-01-01
    • 2021-03-14
    • 1970-01-01
    相关资源
    最近更新 更多