当前位置: 首页 > news >正文

Vue3动态导入后端路由

  1. 动态获取文件
// modules就是一个map,文件路径作为key,文件对象作为value
const modules=import.meta.glob('../views/**/*.vue')

在这里插入图片描述

获取到的modules对象如下:

在这里插入图片描述

  1. 添加动态路由
import {createRouter, createWebHashHistory} from 'vue-router'const modules = import.meta.glob('../views/**/*.vue')const constantRoutes = [{path: '/login',name: 'login',meta: {title: '登录',hidden: true},component: () => import('../views/login/index.vue')},
]const router = createRouter({history: createWebHashHistory(),routes:[…constantRoutes]
})// 从后端动态获取的路由列表,[hidden:是否在侧边栏显示]
let dynamicRoutes = [{path: '/',name: 'Layout',redirect: '/home',component: '/views/layout/index',meta: {title: 'Layout',icon: 'HomeFilled',hidden: false},children: [{path: '/home',name: 'Home',component: '/views/home/index',meta: {title: '首页',icon: 'HomeFilled',hidden: false}},]},{path: '/sys',name: 'Sys',component: '/views/layout/index',meta: {title: '系统管理',icon: 'document',hidden: false},children: [{path: '/sys/user',name: 'User',component: '/views/sys/user/index',meta: {title: '用户管理',icon: 'document',hidden: false}},{path: '/sys/role',name: 'Role',component: '/views/sys/role/index',meta: {title: '角色管理',icon: 'document',hidden: false}},]}
]convertPathToComponent(dynamicRoutes)
addDynamicRoutes(dynamicRoutes)// 添加动态路由
function addDynamicRoutes(dynamicRoutes) {dynamicRoutes.forEach(item => {router.addRoute(item)})
}// 使用递归将routeList中每个对象及其子对象中的component路径转换为组件(在component不为空的情况下)
function convertPathToComponent(dynamicRoutes) {dynamicRoutes.forEach(item => {if (item.component) {item.component = modules['..' + item.component + '.vue'] || modules['../views/404/index.vue']}if (item.children) {convertPathToComponent(item.children)}})
}export default router

http://www.mrgr.cn/news/38612.html

相关文章:

  • [SAP ABAP] SELECT-OPTIONS
  • 深入理解Shapefile格式:点、线、面要素的字节结构解析
  • 带动感的海报艺术!用前端技术点燃你的灵感
  • Cluster Explanation via Polyhedral Descriptions
  • 计算机毕业设计 助农产品采购平台的设计与实现 Java实战项目 附源码+文档+视频讲解
  • 【刷点笔试面试题试试水】不使用任何中间变量如何将a、b的值进行交换?
  • 全球200多个国财政数据(1991-2023年)
  • 一篇文章弄懂数据结构中的各种排序_插入排序_冒泡排序_快速排序_堆排序_归并排序_基数排序
  • 栏目二:Echart绘制动态折线图+柱状图
  • Linux —— Socket编程(二)
  • BUUCTF蜘蛛侠呀
  • Neo4J介绍
  • Go基础学习08-并发安全型类型-通道(chan)深入研究
  • 想做个WPS的自动化代码,参考如下:
  • 制造业智能化建设的指标详解
  • linux安装jdk
  • 【CTF Web】Pikachu 反射型xss(get) Writeup(反射型XSS+GET请求)
  • Unity实战案例全解析:RTS游戏的框选和阵型功能(1) 基础要素
  • AVLTree【c++实现】
  • 2409vim,vim写文件有问题