我正在尝试遵循此处列出的说明:https://github.com/vuejs/vue-class-component#adding-custom-hooks
我没有收到任何错误,但是beforeRouteEnter
无法启动。我没有看到任何控制台输出行。
奇怪的是,如果我在路由器上插入beforeEnter
,则会打印hello
,但不会打印hi
。
下面的示例代码。
class-component-hooks.ts
import { Component } from 'vue-property-decorator';
// Register the router hooks with their names
Component.registerHooks([
'beforeRouteEnter',
'beforeRouteLeave',
'beforeRouteUpdate', // for vue-router 2.2+
]);
main.ts
import './class-component-hooks';
import Vue from 'vue';
import App from './App.vue';
import router from './router';
...
some_component.ts
import { Component, Watch, Vue } from 'vue-property-decorator';
@Component({
...
beforeRouteEnter(to: any, from: any, next: (arg0: (vm: any) => void) => void) {
console.log('hello');
next((vm) => {
// access to component instance via `vm`
console.log('hi');
});
}
})
...
部分触发的场景:
router.ts
{
path: '/a_route',
component: () => import(/* webpackChunkName: "a_route" */ './a_route.vue'),
beforeEnter: (to: any, from: any, next: (arg0: (vm: any) => void) => void) => {
console.log('hello');
next((vm) => {
// access to component instance via `vm`
console.log('hi');
});
},
},
答案 0 :(得分:0)
似乎您已正确完成所有操作,已注册了钩子,并且已在组件定义之前将其导入,但是您的组件类尚未从Vue
继承。
@Component({
...
beforeRouteEnter(to: any, from: any, next: (arg0: (vm: any) => void) => void) {
console.log('hello');
next((vm) => {
// access to component instance via `vm`
console.log('hi');
});
}
})
尝试一下:
import Vue from 'vue'
@Component
class MyComp extends Vue {
...
beforeRouteEnter(to: any, from: any, next: (arg0: (vm: any) => void) => void) {
console.log('hello');
next((vm) => {
// access to component instance via `vm`
console.log('hi');
});
}
}