vue3 vite 根据目录生成路由

vite 勾选 vue-router 搭建好项目后,routes部分示例代码为
routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView
    },
    {
      path: '/about',
      name: 'about',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('../views/AboutView.vue')
    }
  ]

  页面文件在views文件夹,一般用文件夹包含index.vue文件

 关键是用vite读取文件模块的方法

import.meta.glob('/src/views/**/*.vue', { eager: true })

转成示例要的那种格式

Object.keys(views).forEach((path) => {
  routes.push({
    path: path.replace(/^\/src\/views(\/\w+)?\/index\.\w+$/, '$1') ? path.replace(/^\/src\/views(\/\w+)?\/index\.\w+$/, '$1') : '/',
    name: path.replace(/^\/src\/views(\/\w+)?\/index\.\w+$/, '$1').replace('/', ''),
    component: views[path].default,
  });
});

完整代码

import { createRouter, createWebHistory } from 'vue-router'


const routes: any = [];

const views: any = import.meta.glob('/src/views/**/*.vue', { eager: true })

Object.keys(views).forEach((path) => {
  routes.push({
    path: path.replace(/^\/src\/views(\/\w+)?\/index\.\w+$/, '$1') ? path.replace(/^\/src\/views(\/\w+)?\/index\.\w+$/, '$1') : '/',
    name: path.replace(/^\/src\/views(\/\w+)?\/index\.\w+$/, '$1').replace('/', ''),
    component: views[path].default,
  });
});

console.log(routes)


const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})

export default router

 

posted on 2023-10-26 10:42  yxc5354  阅读(165)  评论(0编辑  收藏  举报