/** * @Description: 路由方法 * @Author: zenghua.wang * @Date: 2022-01-26 21:55:58 * @LastEditors: zenghua.wang * @LastEditTime: 2024-04-14 11:03:08 */ import path from 'path-browserify'; import Views from '@/layouts/Views.vue'; import { isEmpty } from './index'; const modules = import.meta.glob('../views/**/**.vue'); /** * 创建路由菜单 * @param {*} menus */ export function createAsyncRoutes(menus = []) { if (isEmpty(menus)) return menus; const res = []; menus.forEach((menu) => { const tmp = { id: menu.id, parentId: menu.parentId, path: menu.path, component: isEmpty(menu.component) ? Views : modules[/* @vite-ignore */ `../views/${menu.component.replace('/views/', '')}`], redirect: menu.redirect ?? null, name: menu.name, meta: { title: menu.title ?? '', icon: menu.icon ?? '', keepAlive: menu.keepAlive ?? false, }, children: menu.children, hidden: menu.hidden ?? false, }; if (tmp.children) { tmp.children = createAsyncRoutes(tmp.children, false); } res.push(tmp); }); return res; } /** * 通过递归过滤异步路由表 * @param routes asyncRoutes * @param roles */ export function filterAsyncRoutes(routes, roles) { const res = []; routes.forEach((route) => { const tmp = { ...route }; if (hasPermission(roles, tmp)) { if (tmp.children) { tmp.children = filterAsyncRoutes(tmp.children, roles); } res.push(tmp); } }); return res; } /** * 使用 meta.role 来确定当前用户是否具有权限 * @param roles * @param route */ export function hasPermission(roles, route) { if (route.meta && route.meta.roles) { return roles.some((role) => route.meta.roles.includes(role)); } else { return false; } } /** * 使用递归,过滤需要缓存的路由 * @param {*} routers * @returns */ export function filterKeepAlive(routers) { const cacheRouter = []; const loop = (routers) => { routers.forEach((item) => { if (item.meta?.keepAlive && item.name) { cacheRouter.push(item.name); } if (item.children && item.children.length) { loop(item.children); } }); }; loop(routers); return cacheRouter; } /** * * @param {*} routers * @param {*} pathUrl */ export function handleRoutes(routers, pathUrl = '') { routers.forEach((item) => { item.path = path.resolve(pathUrl, item.path); }); }