refactor(projects): 路由文件夹拆分模块,代码重构

This commit is contained in:
Soybean
2021-10-11 17:51:16 +08:00
parent f0474bd961
commit 73505d914f
25 changed files with 2408 additions and 2131 deletions

View File

@@ -0,0 +1,35 @@
import type { RouteRecordRaw } from 'vue-router';
function getCacheName(route: RouteRecordRaw, isCache: boolean) {
const cacheNames: string[] = [];
const hasChild = hasChildren(route);
if (isCache && !hasChild) {
const name = route.name as string;
cacheNames.push(name);
}
if (hasChild) {
const children = route.children as RouteRecordRaw[];
children.forEach(item => {
const isChildCache = isCache || isKeepAlive(item);
cacheNames.push(...getCacheName(item, isChildCache));
});
}
return cacheNames;
}
function isKeepAlive(route: RouteRecordRaw) {
return Boolean(route?.meta?.keepAlive);
}
function hasChildren(route: RouteRecordRaw) {
return Boolean(route.children && route.children.length);
}
/** 获取被缓存的路由 */
export default function getCacheRoutes(routes: RouteRecordRaw[]) {
const cacheNames: string[] = [];
routes.forEach(route => {
const isCache = isKeepAlive(route);
cacheNames.push(...getCacheName(route, isCache));
});
return cacheNames;
}

View File

@@ -0,0 +1,19 @@
import type { Component } from 'vue';
import { getLoginModuleRegExp, getRouteNameMap } from '@/utils';
import getCacheRoutes from './cache';
import transformRouteToMenu from './menus';
/** 给需要缓存的页面组件设置名称 */
export function setCacheName(component: Component, name?: string) {
if (name) {
Object.assign(component, { name });
}
}
/** 路由name map */
export const RouteNameMap = getRouteNameMap();
/** 登录模块的正则字符串 */
export const loginModuleRegExp = getLoginModuleRegExp();
export { getCacheRoutes, transformRouteToMenu };

View File

@@ -0,0 +1,46 @@
import type { Component } from 'vue';
import type { CustomRoute, GlobalMenuOption } from '@/interface';
import { dynamicIconRender } from '@/utils';
/** 判断路由是否作为菜单 */
function asMenu(route: CustomRoute) {
return !route.meta?.isNotMenu;
}
/** 给菜单添加可选属性 */
function addPartialProps(menuItem: GlobalMenuOption, icon?: Component, children?: GlobalMenuOption[]) {
const item = { ...menuItem };
if (icon) {
Object.assign(item, { icon: dynamicIconRender(icon) });
}
if (children) {
Object.assign(item, { children });
}
return item;
}
export default function transformRouteToMenu(routes: CustomRoute[]) {
const globalMenu: GlobalMenuOption[] = [];
routes.forEach(route => {
if (asMenu(route)) {
const { name, path, meta } = route;
const routeName = name as string;
let menuChildren: GlobalMenuOption[] | undefined;
if (route.children) {
menuChildren = transformRouteToMenu(route.children as CustomRoute[]);
}
const menuItem: GlobalMenuOption = addPartialProps(
{
key: routeName,
label: meta?.title ?? routeName,
routeName,
routePath: path
},
meta?.icon,
menuChildren
);
globalMenu.push(menuItem);
}
});
return globalMenu;
}