项目源码-Vue3项目03-路由自动生成

Last Updated on 2025年1月5日 by hangzi

路由自动生成

1、查看静态配置的路由

[
  {
    path: '/',
    name: 'index',
    component: () => import('../views/index.vue'),
    meta: {
      title: '首页',
      menuOrder: 1
    }
  },
  {
    path: '/about',
    name: 'about-index',
    component: () => import('../views/about/index.vue'),
    meta: {
      title: '关于',
      menuOrder: 2
    }
  },
  {
    path: '/content',
    name: 'content-index',
    component: () => import('../views/content/index.vue'),
    meta: {
      title: '内容',
      menuOrder: 3
    }
  }
]

2、辅助配置page.js

page.js内容,就是静态路由中的meta对象值:

export default {
    title: '首页',
    menuOrder: 1
}

3、自动生成路由

src/router/index.js完整代码:

import {createRouter, createWebHashHistory} from "vue-router";

//自动生成routes
const pageModules = import.meta.glob('../views/**/page.js',
    {
        eager: true,
        import: 'default'
    });
const comModules = import.meta.glob('../views/**/index.vue');

const routes = Object.entries(pageModules).map(
    ([pagePath, config]) => {
        let path = pagePath.replace('../views', '').replace('/page.js', '');
        path = path || '/';
        const name = path.split('/').filter(Boolean).join('-') || 'index';
        const comPath = pagePath.replace('page.js', 'index.vue')
        return {
            path,
            name,
            component: comModules[comPath],
            meta: config
        }
    }
)

let router = createRouter({
    history: createWebHashHistory(),
    routes,
});

// 全局注册 router
export function setupRouter(app) {
    app.use(router);
}

export default router;

生成的效果:

自动生成路由

项目Demo源码:https://github.com/hangzhi7/Vue3-Demo


关注微信公众号『编程与读书

第一时间了解最新网络动态
关注博主不迷路~