VueJS beforeRouteEnter крюк не стреляет - PullRequest
0 голосов
/ 08 июля 2019

Я пытаюсь следовать инструкциям, изложенным здесь: https://github.com/vuejs/vue-class-component#adding-custom-hooks

Я не получаю никаких ошибок, но beforeRouteEnter не срабатывает. Я не вижу ни одной из строк вывода консоли.

Как ни странно, если я вставлю beforeEnter на мой маршрутизатор, hello будет печатать, но не hi.

Пример кода ниже.

Класс-компонентный-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');
      });
   },
},

1 Ответ

0 голосов
/ 08 июля 2019

Кажется, вы все сделали правильно, вы зарегистрировали хуки и импортировали их до определений компонентов, но ваш класс компонентов не унаследован от 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');
        });
      }
}
...