vite插件,可以读取文件夹下的vue文件,自动生成vue-router的路由信息,这样以后每次有新的vue页面增加,都不用去更改vue-router的路由信息代码了,减少了工作量
npm i -D vite-plugin-pages
npm i -s vue-router@next
import Pages from "vite-plugin-pages"
export default defineConfig({
plugins: [
...
Pages({
// 自动读取src/views下的vue文件,生成路由信息,默认路由路径'/‘
dirs: [{ dir: "src/views", baseRoute: "/" }],
// 异步方式加载路由组件
importMode: "async",
// 遍历路由信息,给默认路由加一个redirect
extendRoute(route) {
if (route.path === "/") return { ...route, redirect: "a" }
}
})
]
})
import { createApp } from "vue"
import App from "./App.vue"
import { createRouter, createWebHashHistory } from "vue-router"
// 这里就是vite-plugin-pages生成的路由信息,正常使用即可
import routes from "virtual:generated-pages"
const router = createRouter({
history: createWebHashHistory(),
routes
})
createApp(App).use(router).mount("#app")
在env.d.ts中加入 ///
///
///
declare module "*.vue" {
import type { DefineComponent } from "vue"
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/ban-types
const component: DefineComponent<{}, {}, any>
export default component
}
那么问题来了,遵循的规则是什么呢?很简单,像示例这样即可,我觉得还是很一目了然的,不用太多介绍
src/views/index.vue -> /
src/views/index/a.vue -> /a // 这里的a.vue就是index.vue的子路由(children)
src/views/father.vue -> /father
src/views/father/son.vue -> /father/son
src/views/father/[id].vue -> /father/:id
src/views/[father]/son.vue -> /:father/son