前言
去年我发布了一篇关于 约定式路由
的文章: 在 vite 中使用 glob 实现约定式路由
文章主要写了关于在 Vite 中使用 glob
根据文件系统自动生成路由,但看到有伙伴介绍这个目前有现成的 vite
插件:vite-plugin-pages
我一时就来了兴趣,搭建了个 vite
工程了解了下,真的可以,而且配置很简单,下面我来介绍一下这个插件的使用
安装插件
- 使用命令搭建一个
vue3
工程:
powershell
pnpm create vite vue3-demo -- --template vue-ts
- 安装
vue-router
和vite-plugin-pages
:
powershell
pnpm add vue-router
pnpm add vite-plugin-pages -D
配置插件
- 打开
vite.config.ts
文件,新增配置:
ts
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import pages from 'vite-plugin-pages'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
vue(),
pages({
dirs: "src/views", // 需要生成路由的文件目录,默认就是识别src下面的pages文件
exclude: ["**/components/*.vue"], // 排除在外的目录,上面配置目录的例子,里面有 components 目录,我们不希望他被解析为路由
extendRoute(route, parent) {
if (route.path === '/') {
//给默认路由加一个redirect,默认为index.vue
return {
...route,
redirect: '/about'
}
}
}
}),
]
})
- 配置
router/index.ts
路由文件:
ts
import {
createRouter,
createWebHistory
} from "vue-router";
import routes from "~pages";
const router = createRouter({
history: createWebHistory(),
routes,
});
export default router;
main.ts
中挂载路由:
ts
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import router from './router'
createApp(App).use(router).mount('#app')
文件系统即是路由
- 我们简单创建几个菜单文件:
- 我们在
router/index.ts
打印一下routes
,会得到默认的路由配置,这时候我们就可以访问路由了: - 如果我们想覆盖
route
配置,可以在文件中添加<route>
路由信息:
vue
<route>
{
name:'new-about',
meta: {
requiresAuth: false,
layout:'top'
}
}
</route>
<route>
里面的配置会直接覆盖默认配置,你也可以使用 yaml
格式:
yaml
<route lang="yaml">
name: new-about
meta:
requiresAuth: true
layout: top
</route>
- 配置动态路由,只需要用
[]
符号包裹:
txt
src/pages/users/[id].vue -> /users/:id (/users/one)
src/pages/[user]/settings.vue -> /:user/settings (/one/settings)
- 配置
404
拦截页面,在src/views
目录下添加[...all].vue
:
路由生成规则
txt
src/views/index.vue -> /
src/views/index/a.vue -> /a // 这里的a.vue就是index.vue的子路由(children)
src/views/father/index.vue -> /father
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
src/views/[...all].vue ->文件用来适配404页面
更多配置请参考:vite-plugin-pages
总结
个人感觉这个插件功能还是挺实用的,可以用在我们的项目上,就不用每次都要手写路由配置了,也更加容易维护。
不得不感叹现在前端开发的工具真的是越来越多了,也越来越实用,vite
还有很多实用的功能待我们去探索,这里给作者和 尤雨溪
老板一个赞👍🏻🫰