【问题标题】:How do I properly type navigation guards in Nuxt class components?如何在 Nuxt 类组件中正确键入导航守卫?
【发布时间】:2022-01-16 23:21:30
【问题描述】:

我有一个带有 Typescript 和 beforeRouteLeave 钩子的 Nuxt 类组件,如下所示:

import { Component, Vue } from "nuxt-property-decorator"

@Component
export default class MyComponent extends Vue {
  beforeRouteLeave (_to, _from, next) {
    this.foo()
    next()
  }

  foo () { console.log("navigation guard triggered") }
}

这会引发 TS 错误,因为 _to, _from, next implicitly have an any type。所以我尝试将方法输入为 Vue 路由器 NavigationGuard,如下所示:

import { Component, Vue } from "nuxt-property-decorator"
import type { NavigationGuard } from "vue-router"

@Component
export default class MyComponent extends Vue {
  beforeRouteLeave: NavigationGuard = function (this: MyComponent, to, _from, next) { // without typing `this` the next line throws an error
    this.foo()
    next()
  }

  foo () { console.log("navigation guard triggered") }
}

TS 错误已消失,但未在应用中触发挂钩。我做错了什么?

【问题讨论】:

    标签: typescript vue.js nuxt.js


    【解决方案1】:
    1. 您应该在您的自定义插件中注册 registerHooks lifeCycle 并将其注册到nuxt.config.ts
    // plugin/main.ts
    import 'vue-class-component/hooks' // auto registerHooks
    
    // nuxt.config.ts
    import type { NuxtConfig } from '@nuxt/types';
    const config: NuxtConfig = {
         plugins: [ { src: '~/plugins/main.ts' } ]
         // ignore other...
    };
    export default config;
    
    1. 根据docbeforeRouteLeave 有两个或三个参数,而不是四个,因此只需修复代码即可。
    // MyComponent.vue
    import { Component, Vue } from "nuxt-property-decorator"
    import { NavigationGuardNext, Route } from 'vue-router';
    
    @Component
    export default class MyComponent extends Vue {  
      beforeRouteLeave(to: Route, from: Route, next: NavigationGuardNext) {
        // will call the foo() function
        this.foo()
        next()
      }
    
      foo () { console.log("navigation guard triggered") }
    }
    
    1. 如果您的 VSCode 仍然显示缺少类型,您可以创建 shims-vue.d.ts 以帮助 Typescript 了解类型。这里是doc

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-26
      • 1970-01-01
      • 2019-10-21
      • 1970-01-01
      • 2020-11-02
      • 1970-01-01
      • 2018-02-21
      • 2021-06-01
      相关资源
      最近更新 更多