Skip to content
该翻译已同步到了 的版本,其对应的 commit hash 是 d842b6f

入门

Vue Router 内置了基于文件的路由插件。它会自动从你的页面组件生成路由和类型,因此你不再需要手动维护 routes 数组。

设置

将插件添加到你的打包工具中:

ts
import VueRouter from 'vue-router/vite'

export default defineConfig({
  plugins: [
    VueRouter({
      /* options */
    }),
    // ⚠️ Vue 必须放在 VueRouter() 之后
    Vue(),
  ],
})
ts
import VueRouter from 'vue-router/unplugin/rollup'

export default {
  plugins: [
    VueRouter({
      /* options */
    }),
    // ⚠️ Vue 必须放在 VueRouter() 之后
    Vue(),
  ],
}
ts
module.exports = {
  /* ... */
  plugins: [
    require('vue-router/unplugin/webpack')({
      /* options */
    }),
  ],
}
ts
module.exports = {
  configureWebpack: {
    plugins: [
      require('vue-router/unplugin/webpack')({
        /* options */
      }),
    ],
  },
}
ts
import { build } from 'esbuild'
import VueRouter from 'vue-router/unplugin/esbuild'

build({
  plugins: [VueRouter()],
})

添加此插件后,启动开发服务器(通常是 npm run dev)在 typed-router.d.ts 生成第一版本的类型文件,该文件应该与 "moduleResolution": "Bundler" 一起添加到你的 tsconfig.json 中。它应该看起来像这样:

json
{
  "include": [
    // 其他文件...
    "./typed-router.d.ts"
  ],
  "compilerOptions": {
    // ...
    "moduleResolution": "Bundler",
    // ...
  }
}
ts
/* eslint-disable */
/* prettier-ignore */
// @ts-nocheck
// Generated by vue-router. ‿️ 不要修改此文件 ‿️
// 建议提交此文件。
// 确保将此文件作为 "includes" 或 "files" 条目添加到你的 tsconfig.json 文件中。

declare module 'vue-router/auto-routes' {
  import type {
    RouteRecordInfo,
    ParamValue,
    ParamValueOneOrMore,
    ParamValueZeroOrMore,
    ParamValueZeroOrOne,
  } from 'vue-router'

  /**
   * Vue Router 基于文件的路由生成的路由名称映射
   */
  export interface RouteNamedMap {
    '/': RouteRecordInfo<
      '/',
      '/',
      Record<never, never>,
      Record<never, never>,
      | never
    >
    '/about': RouteRecordInfo<
      '/about',
      '/about',
      Record<never, never>,
      Record<never, never>,
      | never
    >
    '/users/[id]': RouteRecordInfo<
      '/users/[id]',
      '/users/:id',
      { id: ParamValue<true> },
      { id: ParamValue<false> },
      | never
    >
  }
}

然后,如果你有一个 env.d.ts 文件,将 vue-router/auto 类型添加到其中:

ts
/// <reference types="vite/client" />
/// <reference types="vue-router/auto" />

如果你没有 env.d.ts 文件,你可以创建一个,或者在 tsconfig.jsontypes 属性中添加:

json
{
  "compilerOptions": {
    // ...
    "types": [
      "vue-router/auto"
    ]
  }
}

迁移现有项目

将你的页面组件移动到 src/pages 并相应地重命名它们。以下是一个迁移示例。 给定以下路由配置:

ts
import { createRouter, createWebHistory } from 'vue-router'
import { routes, handleHotUpdate } from 'vue-router/auto-routes'

export const router = createRouter({
  history: createWebHistory(),
  routes: [ 
    { 
      path: '/', 
      component: () => import('src/pages/Home.vue'), 
    }, 
    { 
      path: '/users/:id', 
      component: () => import('src/pages/User.vue'), 
    } 
    { 
      path: '/about', 
      component: () => import('src/pages/About.vue'), 
    }, 
  ] 
  routes, 
})

// 这将在运行时更新路由而无需重新加载页面
if (import.meta.hot) { 
  handleHotUpdate(router) 
} 
ts
import { createApp } from 'vue'
import { router } from './router'
import App from './App.vue'

createApp(App).use(router).mount('#app')
  • src/pages/Home.vue 重命名为 src/pages/index.vue
  • src/pages/User.vue 重命名为 src/pages/users/[id].vue
  • src/pages/About.vue 重命名为 src/pages/about.vue

查看 文件约定 指南以获取有关命名约定的更多信息。

从头开始

  • 创建一个 src/pages 文件夹并在其中添加一个 index.vue 组件。这将在 / 渲染你的主页。
  • vue-router/auto-routes 导入 routes 并将其传递给 createRouter 函数。
ts
import { createApp } from 'vue'
import { createRouter, createWebHistory } from 'vue-router'
import { routes } from 'vue-router/auto-routes'
import App from './App.vue'

const router = createRouter({
  history: createWebHistory(),
  routes,
})

createApp(App)
  .use(router)
  .mount('#app')
vue
<template>
  <h1>首页</h1>
</template>

查看 文件约定 指南以获取有关命名约定的更多信息。

修改路由

你可以将 routes 传递给任何需要对其进行修改的插件,但请注意这些更改不会反映在类型中。如果你想要类型支持,请改用 构建时路由。以下是使用 Vitesse 启动器 的示例:

ts
import { ViteSSG } from 'vite-ssg'
import { setupLayouts } from 'virtual:generated-layouts'
import App from './App.vue'
import type { UserModule } from './types'
import generatedRoutes from '~pages'
import { routes } from 'vue-router/auto-routes'

import '@unocss/reset/tailwind.css'
import './styles/main.css'
import 'uno.css'

const routes = setupLayouts(generatedRoutes) 

// https://github.com/antfu/vite-ssg
export const createApp = ViteSSG(
  App,
  {
    routes, 
    routes: setupLayouts(routes), 
    base: import.meta.env.BASE_URL,
  },
  ctx => {
    // install all modules under `modules/`
    Object.values(
      import.meta.glob<{ install: UserModule }>('./modules/*.ts', {
        eager: true,
      })
    ).forEach(i => i.install?.(ctx))
  }
)

自动导入

如果你使用 unplugin-auto-import,请确保删除 vue-router 预设并使用 vue-router 导出的预设:

ts
import { defineConfig } from 'vite'
import AutoImport from 'unplugin-auto-import/vite'
import { VueRouterAutoImports } from 'vue-router/unplugin'

export default defineConfig({
  plugins: [
    // 其他插件
    AutoImport({
      imports: [
        'vue-router', 
        VueRouterAutoImports, 
      ],
    }),
  ],
})

如果你使用 ESLint,请查看 ESLint 部分

Released under the MIT License.