I'm trying to implement Vue Router's in-component navigation guards using the vue-property-decorator package. Underlying, vue-property-decorator relies on vue-class-component package. It offers a registerHooks
method, allowing you to declare what methods should be treated as lifecycle hooks (instead of instance methods).
The following code works, resulting in an alert when entering the route:
import { Component, Vue } from 'vue-property-decorator';
import { router } from './Router';
@Component({
template: '<div></div>'
})
export class Foo extends Vue {
beforeRouteEnter(to, from, next){
alert('Entering Foo');
next();
}
}
router.addRoutes([
{ path: '/foo', component: Foo }
]);
The Router.ts file contains the hook registration as per the docs and is exactly:
import VueRouter from 'vue-router';
import { Component } from 'vue-property-decorator'
Component.registerHooks([
'beforeRouteEnter',
'beforeRouteUpdate',
'beforeRouteLeave'
]);
export const router = new VueRouter({
mode: 'abstract'
});
The router file is imported in an App.ts file, before the components are imported, hence the hooks are registered before the components are.
However, I seem to be unable to pass in a callback to the next
method. Given the updated Foo
component from above:
import { Component, Vue } from 'vue-property-decorator';
import { router } from './Router';
@Component({
template: '<div></div>'
})
export class Foo extends Vue {
beforeRouteEnter(to, from, next){
next(vm => {
alert('Entering Foo');
});
}
}
The alert is never fired. Am I missing something, or it this a bug in the vue-class-component package? I should add that I'm also unable to pass the callback to the next function in the per route and global route navigation guards.
Many thanks in advance for any help, greatly appreciated!
Please move your beforeRouteEnter hook to @Component
decorator
@Component({
template: '<div></div>',
beforeRouteEnter(to, from, next){
next(vm => {
alert('Entering Foo');
});
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With