Route Guard vue3 中的参数(route、from、next)类型

BT1*_*101 4 typescript vue.js vuejs3

我导出一个函数,并将其传递给router.beforeEach

export default function (route, from, next) {
  log.debug(route.path)

  if (!identity.state.authenticated) {
    log.debug('redirecting to "login" view...')
    next({ name: 'login' })
  } else {
    next()
  }
}
Run Code Online (Sandbox Code Playgroud)

但这会导致 3 个 TypeScript 错误:

TS7006: Parameter 'route' implicitly has an 'any' type.
TS7006: Parameter 'from' implicitly has an 'any' type.
TS7006: Parameter 'next' implicitly has an 'any' type.
Run Code Online (Sandbox Code Playgroud)

什么类型最适合这些人?我可以让它们只是对象,但是没有一些类型可以从中导入吗vue

ton*_*y19 7

router.beforeEach键入为:

beforeEach(guard: NavigationGuardWithThis<undefined>): () => void
Run Code Online (Sandbox Code Playgroud)

NavigationGuardWithThis输入

export interface NavigationGuardWithThis<T> {
  (
    this: T,
    to: RouteLocationNormalized,
    from: RouteLocationNormalized,
    next: NavigationGuardNext
  ): NavigationGuardReturn | Promise<NavigationGuardReturn>
}
Run Code Online (Sandbox Code Playgroud)

因此,您需要从以下位置导入这些类型vue-router

import { RouteLocationNormalized, NavigationGuardNext } from 'vue-router'

export default function(
  to: RouteLocationNormalized,
  from: RouteLocationNormalized,
  next: NavigationGuardNext
) {
  /*...*/
}
Run Code Online (Sandbox Code Playgroud)