Vue路由自动化配置

根据文件进行自动化导入,路由配置,无需再手动编写路由配置

本文章给基于vite+vue3构建,具体自动化构建工具需要查看具体的技术文档提供的模块。

注意:真实有效,本人在大项目级别中已投入使用,性能和手动导入几乎没有差别,甚至能动态控制路由的创建与销毁,实现高效的路由导航。优势:

  1. 大幅度减轻繁琐的重复性的工作
  2. 能适用于任何项目
  3. 大幅度提高项目构建成本
  4. 适用于多人协作开发,压根不会影响到别人新建路由的配置文件的修改
  5. 降低代码多人开发冲突风险

 配置规则:

同级路径下创建index.vue文件与page.json文件,将自动读取到index,设置page.json的配置信息

page.json文件

{
  "title": "系统",
  "menuOrder": 1,
  "menuName": "Home",
  "menuIcon": "内容",
  "showMenu": true
}

@/router/modules/system.js文件创建重定向脚本


import Layout from '@/layout/index.vue'

export default [
  {
    path: '/',
    redirect: '/home',
  },
  // {
  //   path: '/layout',
  //   component: Layout,
  //   name: 'layout',
  //   children: []
  // }
]

在router.js文件中进行引入使用

import { createRouter, createWebHistory } from 'vue-router';
import { buildRouteTree, toRouteName } from "@/utils/routeTree"
import system from '@/router/modules/system.js';


// 使用 import.meta.glob 动态导入 page.json 和 Vue 组件
const pageModules = import.meta.glob('../views/**/page.json', { eager: true, import: 'default' });
const compModules = import.meta.glob('../views/**/index.vue');

let treeRouterList = []
// 将 pageModules 转换为数组
var routes = Object.entries(pageModules).map(([pagePath, config]) => {
  // 从路径中创建路由路径和名称
  treeRouterList.push(pagePath);
  // 返回路由对象
  return detailRouter(pagePath,config)
});


function detailRouter(pagePath,config){
  let path = pagePath.replace('../views', '').replace('/page.json', '');
  path = path || '/';
  const name = toRouteName(path);
  // 创建组件路径
  const compPath = pagePath.replace('page.json', 'index.vue');
  // parentPath
  const parentPath = path.split('/').slice(0, -1).join('/');
  // 返回路由对象
  return {
    path: config.path ? config.path : path,
    name: config.name ? config.name : name,
    component: compModules[compPath],
    meta: {parentPath: parentPath,...config},
    children: [],// 子路由
  };
}

// 添加重定向路由
routes = [...routes,...system]
console.log(system);

const routeTree = buildRouteTree(routes);

// 创建并导出路由实例
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: routeTree,
});

// 路由拦截 具体操作 根据项目编写
// router.beforeEach((to, from, next) => {
//   next()
// })

export default router;

路由处理工具

function toRouteName(path) {
  return path
    .split('/')
    .filter(Boolean)
    .map(segment => segment.charAt(0).toUpperCase() + segment.slice(1))
    .join('');
}


function buildRouteTree(routes) {
  const tree = [];
  const lookup = {};

  // Initialize lookup with paths
  routes.forEach(route => {
    if (route.path) {
      lookup[route.path] = { ...route, children: [] };
    }
  });

  // Build the tree
  routes.forEach(route => {
    if (route.redirect) {
      tree.push(route);
    } else {
      const parentPath = route.meta?.parentPath;
      if (parentPath && lookup[parentPath]) {
        lookup[parentPath].children.push(lookup[route.path]);
      } else {
        tree.push(lookup[route.path]);
      }
    }
  });

  return tree;
}

export {
  toRouteName,
  buildRouteTree
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值