Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 430
thomaux Avatar asked Sep 03 '18 11:09

thomaux


1 Answers

Please move your beforeRouteEnter hook to @Component decorator

@Component({
    template: '<div></div>',
    beforeRouteEnter(to, from, next){
        next(vm => {
            alert('Entering Foo');
        });
    }
})
like image 50
Evgeniy Voytenko Avatar answered Oct 02 '22 17:10

Evgeniy Voytenko