如何使用 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)
}
相关推荐
Mr.Jessy1 小时前
JavaScript高级:构造函数与原型
开发语言·前端·javascript·学习·ecmascript
白兰地空瓶3 小时前
🚀你以为你在写 React?其实你在“搭一套前端操作系统”
前端·react.js
爱上妖精的尾巴3 小时前
6-4 WPS JS宏 不重复随机取值应用
开发语言·前端·javascript
似水流年QC4 小时前
深入探索 WebHID:Web 标准下的硬件交互实现
前端·交互·webhid
陪我去看海4 小时前
测试 mcp
前端
speedoooo5 小时前
在现有App里嵌入一个AI协作者
前端·ui·小程序·前端框架·web app
全栈胖叔叔-瓜州5 小时前
关于llamasharp 大模型多轮对话,模型对话无法终止,或者输出角色标识User:,或者System等角色标识问题。
前端·人工智能
三七吃山漆5 小时前
攻防世界——wife_wife
前端·javascript·web安全·网络安全·ctf
用户47949283569155 小时前
面试官问"try-catch影响性能吗",我用数据打脸
前端·javascript·面试
GISer_Jing5 小时前
前端营销技术实战:数据+AI实战指南
前端·javascript·人工智能