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

vue3 + vite 实现一个动态路由加载功能

假设后端返回的格式是这样子

{"menu": [{"path": "/admin","name": "adminLayout","redirect": "/admin/index","componentPath": "/layout/admin/index.vue","children": [{"path": "index","name": "Index","meta": {"title": "首页","keepAlive": true,"requireAuth": true},"componentPath": "/views/index/index.vue"},{"path": "logic-flow","name": "LogicFlow","meta": {"title": "可视化拖拽","keepAlive": true,"requireAuth": true},"componentPath": "/views/logic-flow/index.vue"},{"path": "custom-form","name": "CustomForm","meta": {"title": "自定义表单","keepAlive": true,"requireAuth": true},"componentPath": "/views/custom-form/index.vue"},{"path": "big-screen","name": "BigScreen","meta": {"title": "可视化大屏","keepAlive": true,"requireAuth": true},"componentPath": "/views/big-screen/index.vue"},{"path": "d3","name": "D3","meta": {"title": "D3","keepAlive": true,"requireAuth": true},"componentPath": "/views/d3/index.vue"},{"path": "konva","name": "Konva","meta": {"title": "Konva","keepAlive": true,"requireAuth": true},"componentPath": "/views/konva/index.vue"},{"path": "/function","name": "Function","redirect": "/function/index","children": [{"path": "large-file-upload","name": "LargeFileUpload","meta": {"title": "LargeFileUpload","keepAlive": true,"requireAuth": true},"componentPath": "/views/function/large-file-upload/index.vue"},{"path": "virtual-list","name": "VirtualList","meta": {"title": "VirtualList","keepAlive": true,"requireAuth": true},"componentPath": "/views/function/virtual-list/index.vue"}]}]},{"path": "/data-chart","name": "DataChart","meta": {},"componentPath": "/views/big-screen/data-chart.vue"}]
}

在vite里主要使用到的方法是import.meta.glob,它能通过我们提供的路径动态引入相关的组件,如果我们传入了../views/**/**.vue,它返回的相关格式是这样子,这样的话就可以用过路径获取相关异步导入组件的函数了

完整代码如下(permission.ts):

import router from './index'
import { RouteRecordRaw } from 'vue-router'
import { useUserStore } from '@/store/modules/user'const viewsModules = import.meta.glob('../views/**/**.vue')
const layoutModules = import.meta.glob('../layout/*/*.vue')// 这个方法主要就是将componentPath转成异步引入函数component
const menuToRoutes = (menus: RouteRecordRaw[]) => {if (!menus || !menus.length) {return []}const routes: RouteRecordRaw[] = []menus.forEach((item: any) => {const meta = Object.assign({}, item.meta)let componentif (item.componentPath) {// 如果找不到就给个404的组件component =viewsModules[`..${item.componentPath}`] ||layoutModules[`..${item.componentPath}`] ||viewsModules['../views/404/index.vue']}routes.push({meta,name: item.path,path: item.path,component: component,redirect: item.redirect,children: menuToRoutes(item.children),})})return routes
}export const setupPermission = () => {router.beforeEach((to, from, next) => {const userStore = useUserStore()if (!userStore.menu.length) {// 获取路由// userStore.menu就是json里的menu字段userStore.setMenu().then(() => {// 动态路由注册router.addRoute({path: '/',redirect: '/admin',children: menuToRoutes(userStore.menu),})next({ ...to, replace: true })}).catch(() => {next()})} else {next()}})
}

最后在main.js里调用一下setupPermission方法就行~

PS: 如果退出登录需要清除动态路由的话,因为现在vue-router没有提供可以直接清空的方法,所以可以考虑返回登录页后刷新一下界面来解决~

http://www.lryc.cn/news/321437.html

相关文章:

  • 【征稿进行时|见刊、检索快速稳定】2024年区块链、物联网与复合材料与国际学术会议 (ICBITC 2024)
  • 若依jar包运行脚本,从零到一:用Bash脚本实现JAR应用的启动、停止与监控
  • Unix运维_FreeBSD-13.1临时环境变量设置(bin和include以及lib)
  • Apache Dolphinscheduler - 无需重启 Master-Server 停止疯狂刷日志解决方案
  • 竞争优势:大型语言模型 (LLM) 如何重新定义业务策略
  • Spring AOP和AspectJ AOP区别
  • FREERTOS信号量详解
  • 每天学习一个Linux命令之vim
  • linux环境部署
  • 上位机图像处理和嵌入式模块部署(qmacvisual图像预处理)
  • C语言内存函数详解
  • 详解Redis的持久化RDB和AOF
  • 详细分析Js中的Promise.all基本知识(附Demo)
  • const,static深度总结——c++穿透式分析
  • 快速搭建一个一元二次方程flask应用
  • O2OA红头文件流转与O2OA版式公文编辑器基本使用
  • 软件测试:C++ Google Test单元测试框架GTest
  • 大数据面试题 —— HBase
  • SCI一区 | Matlab实现GWO-TCN-BiGRU-Attention灰狼算法优化时间卷积双向门控循环单元融合注意力机制多变量时间序列预测
  • SpringMVC的执行原理
  • Qt + HTTP 线程交互类封装
  • GitHub Copilot+ESP开发实战-串口
  • C# 使用ffmpeg将图片保存为mp4视频
  • Java安全技术及代码审计技巧
  • C# 使用OpenCvSharp4将Bitmap合成为MP4视频的环境
  • [游戏开发][Unity] 导出Xcode工程,完成调试与发布
  • JSONP 实现跨域请求案例
  • 2024年智慧城市、人文发展与区域经济国际会议(ICSCCDRE 2024)
  • 目标检测——PP-YOLO算法解读
  • 多特征变量序列预测(11) 基于Pytorch的TCN-GRU预测模型