npm i vite-plugin-pages vite-plugin-vue-layouts -D
官方文档 https://github.com/hannoeru/vite-plugin-pages
import Pages from 'vite-plugin-pages' // 插件里面 plugins: [ Pages({ dirs: 'src/views', // 需要生成路由的文件的目录 exclude: ['**/components/*.vue'] // 排除在外的目录,将所有 components 目录下的 .vue 文件排除 }) ]
import { createRouter, createWebHashHistory } from 'vue-router' import routes from '~pages' routes.push({ path: '/', redirect: '/login', }); const router = createRouter({ history: createWebHashHistory(), // HashHistory routes, }) export default router
然后就可以自动生成路由了,是不是很方便
src/views/index.vue -> /
src/views/index/home.vue -> / // 这里的home.vue就是index.vue的子路由(children)
src/views/user.vue -> /user
src/views/user/son.vue -> /user/son
src/views/user/[id].vue -> /user/:id
src/views/[user]/son.vue -> /:user/son