跳至内容

类型化路由 v4.4.0+

危险

‼️ 实验性功能

RouterLink to autocomplete

可以配置路由以拥有类型化路由的映射。虽然可以手动完成,但建议使用 unplugin-vue-router 插件自动生成路由和类型。

手动配置

以下是如何手动配置类型化路由的示例

ts
// import the `RouteRecordInfo` type from vue-router to type your routes
import type { RouteRecordInfo } from 'vue-router'

// Define an interface of routes
export interface RouteNamedMap {
  // each key is a name
  home: RouteRecordInfo<
    // here we have the same name
    'home',
    // this is the path, it will appear in autocompletion
    '/',
    // these are the raw params. In this case, there are no params allowed
    Record<never, never>,
    // these are the normalized params
    Record<never, never>
  >
  // repeat for each route..
  // Note you can name them whatever you want
  'named-param': RouteRecordInfo<
    'named-param',
    '/:name',
    { name: string | number }, // raw value
    { name: string } // normalized value
  >
  'article-details': RouteRecordInfo<
    'article-details',
    '/articles/:id+',
    { id: Array<number | string> },
    { id: string[] }
  >
  'not-found': RouteRecordInfo<
    'not-found',
    '/:path(.*)',
    { path: string },
    { path: string }
  >
}

// Last, you will need to augment the Vue Router types with this map of routes
declare module 'vue-router' {
  interface TypesConfig {
    RouteNamedMap: RouteNamedMap
  }
}

提示

这确实很繁琐且容易出错。这就是为什么建议使用 unplugin-vue-router 自动生成路由和类型。