Vue Router with vue-class-component: next function does not accept callback option
Asked Answered
O

1

6

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 nextmethod. 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!

Outstretch answered 3/9, 2018 at 11:5 Comment(1)
I encountered similar problem, but thanks to your post , I see that I have to register explicitly this router hooks, so my problem has been solved. Hope you figure yours out~Dossal
J
10

Please move your beforeRouteEnter hook to @Component decorator

@Component({
    template: '<div></div>',
    beforeRouteEnter(to, from, next){
        next(vm => {
            alert('Entering Foo');
        });
    }
})
Jackscrew answered 5/7, 2019 at 9:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.