网上便搜如何Vue3.0+ts的情况下在default class中直接使用
全都是这样的

Component.registerHooks([
  "beforeRouteEnter"
  'beforeRouteLeave',
  'beforeRouteUpdate'
]);

但事实是新的vue-class-component组件中Component上未声明registerHooks
看了源码后发现registerHooks是直接声明在VueConstructor接口上是Vue的类型声明
源码截图
故直接使用Vue.registerHooks

<template>
  <div class="home">
    <img alt="Vue logo" src="../assets/logo.png" />
    <hello-world msg="Welcome to Your Vue.js + TypeScript App" />
  </div>
</template>

<script lang="ts">
import { Options, Vue } from "vue-class-component";
import HelloWorld from "@/components/HelloWorld.vue"; // @ is an alias to /src
import { NavigationGuardNext, RouteLocationNormalized } from "vue-router";
Vue.registerHooks([
  "beforeRouteEnter"
  // 'beforeRouteLeave',
  // 'beforeRouteUpdate'
]);
@Options({
  name: "DefaultExamples",
  components: {
    HelloWorld
  }
})
export default class DefaultExamples extends Vue {
  beforeRouteEnter(
    to: RouteLocationNormalized,
    from: RouteLocationNormalized,
    next: NavigationGuardNext
  ) {
    console.log("beforeRouteEnter-to-from:", to, from, next);
    next();
  }
}
</script>

成功拦截

Logo

前往低代码交流专区

更多推荐