如何使用 Vue Router 的类型化路由

在 vue-router 4.4.0+ 版本中,你可以使用插件来增强 Vue Router 在 TS 项目中的使用体验。

如果你使用 Vite 作为构建工具,那么可以使用 unplugin-vue-router 插件来自动化生成路由和类型。 当然你也可以手动进行配置,但是这很容易出错。

安装

我们可以先安装 unplugin-vue-router 插件:

bash 复制代码
pnpm i -D unplugin-vue-router

配置

vite.config.ts 中配置插件:

ts 复制代码
import vue from '@vitejs/plugin-vue'
import VueRouter from 'unplugin-vue-router/vite'
import { defineConfig } from 'vite'

// https://vite.dev/config/
export default defineConfig({
    plugins: [
        VueRouter(), // 这个插件需要放到 Vue 插件之前
        vue()
    ],
})

配置 tsconfig.json 文件

json{3,5,6} 复制代码
{
  "files": [],
  "include": ["./typed-router.d.ts"],
  "compilerOptions": {
    "moduleResolution": "Bundler",
    "types": ["unplugin-vue-router/client"]
  },
  "references": [{ "path": "./tsconfig.app.json" }, { "path": "./tsconfig.node.json" }]
}

配置 vite-env.d.ts

ts 复制代码
// env.d.ts
/// <reference types="vite/client" />
/// <reference types="unplugin-vue-router/client" />

使用

vue-router/auto-routes 导入生成的 routes,将它传递给 CreateRouter

ts 复制代码
import { createRouter, createWebHistory } from 'vue-router'
import { routes } from 'vue-router/auto-routes'

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

然后,我们就可以在 src/pages 目录下创建文件了,所有的 vue 文件都会被视为一个页面,会自动生成路由。生成的 TS 类型文件会保存在 typed-router.d.ts 中。

这样我们在使用 router-link 或者 router.push 时,就可以获得类型提示了。

其余配置

插件其余配置

我们可以在vite.config.ts中配置其余参数

ts{9-11} 复制代码
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import VueRouter from 'unplugin-vue-router/vite'

// https://vite.dev/config/
export default defineConfig({
  plugins: [
    VueRouter({
      dts: '/types/typed-router.d.ts', // 指定生成的类型文件路径
      exclude: ["**/components/**", "**/layouts/**",'**/data/**', '**/types/**'], // 排除不需要生成路由的文件
      extensions: ['vue'], // 支持的文件扩展名
    }), // 这个插件需要放到 Vue 插件之前
    vue()
  ],
})

热重载

配置热重载,在创建文件时更新路由类型文件

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

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

if (import.meta.env) {
    handleHotUpdate(router)
}
相关推荐
一 乐8 分钟前
民宿|基于java的民宿推荐系统(源码+数据库+文档)
java·前端·数据库·vue.js·论文·源码
testleaf37 分钟前
前端面经整理【1】
前端·面试
BillKu38 分钟前
Vue3 + TypeScript + Element Plus 表格行按钮不触发 row-click 事件、不触发勾选行,只执行按钮的 click 事件
vue.js·elementui·typescript
好了来看下一题38 分钟前
使用 React+Vite+Electron 搭建桌面应用
前端·react.js·electron
啃火龙果的兔子39 分钟前
前端八股文-react篇
前端·react.js·前端框架
小前端大牛马1 小时前
react中hook和高阶组件的选型
前端·javascript·vue.js
刺客-Andy1 小时前
React第六十二节 Router中 createStaticRouter 的使用详解
前端·javascript·react.js
萌萌哒草头将军3 小时前
🚀🚀🚀VSCode 发布 1.101 版本,Copilot 更全能!
前端·vue.js·react.js
GIS之路3 小时前
OpenLayers 图层叠加控制
前端·信息可视化
90后的晨仔3 小时前
ArkTS 语言中的number和Number区别是什么?
前端·harmonyos