feat(projects): new router system [新的路由系统]

This commit is contained in:
Soybean
2022-11-08 01:14:59 +08:00
parent 40c1e13b50
commit c7b6a3fbec
54 changed files with 1328 additions and 759 deletions

View File

@ -4,7 +4,7 @@
* @param menus - 菜单数据
* @param rootPath - 根路由路径
*/
export function getBreadcrumbByRouteKey(activeKey: string, menus: GlobalMenuOption[], rootPath: string) {
export function getBreadcrumbByRouteKey(activeKey: string, menus: App.GlobalMenuOption[], rootPath: string) {
const breadcrumbMenu = getBreadcrumbMenu(activeKey, menus);
const breadcrumb = breadcrumbMenu.map(item => transformBreadcrumbMenuToBreadcrumb(item, rootPath));
return breadcrumb;
@ -15,8 +15,8 @@ export function getBreadcrumbByRouteKey(activeKey: string, menus: GlobalMenuOpti
* @param activeKey - 当前页面路由的key
* @param menus - 菜单数据
*/
function getBreadcrumbMenu(activeKey: string, menus: GlobalMenuOption[]) {
const breadcrumbMenu: GlobalMenuOption[] = [];
function getBreadcrumbMenu(activeKey: string, menus: App.GlobalMenuOption[]) {
const breadcrumbMenu: App.GlobalMenuOption[] = [];
menus.some(menu => {
const flag = activeKey.includes(menu.routeName);
if (flag) {
@ -32,15 +32,15 @@ function getBreadcrumbMenu(activeKey: string, menus: GlobalMenuOption[]) {
* @param activeKey - 当前页面路由的key
* @param menu - 单个菜单数据
*/
function getBreadcrumbMenuItem(activeKey: string, menu: GlobalMenuOption) {
const breadcrumbMenu: GlobalMenuOption[] = [];
function getBreadcrumbMenuItem(activeKey: string, menu: App.GlobalMenuOption) {
const breadcrumbMenu: App.GlobalMenuOption[] = [];
if (activeKey === menu.routeName) {
breadcrumbMenu.push(menu);
}
if (activeKey.includes(menu.routeName) && menu.children && menu.children.length) {
breadcrumbMenu.push(menu);
breadcrumbMenu.push(
...menu.children.map(item => getBreadcrumbMenuItem(activeKey, item as GlobalMenuOption)).flat(1)
...menu.children.map(item => getBreadcrumbMenuItem(activeKey, item as App.GlobalMenuOption)).flat(1)
);
}
@ -52,9 +52,9 @@ function getBreadcrumbMenuItem(activeKey: string, menu: GlobalMenuOption) {
* @param menu - 单个菜单数据
* @param rootPath - 根路由路径
*/
function transformBreadcrumbMenuToBreadcrumb(menu: GlobalMenuOption, rootPath: string) {
function transformBreadcrumbMenuToBreadcrumb(menu: App.GlobalMenuOption, rootPath: string) {
const hasChildren = Boolean(menu.children && menu.children.length);
const breadcrumb: GlobalBreadcrumb = {
const breadcrumb: App.GlobalBreadcrumb = {
key: menu.routeName,
label: menu.label as string,
routeName: menu.routeName,
@ -66,7 +66,7 @@ function transformBreadcrumbMenuToBreadcrumb(menu: GlobalMenuOption, rootPath: s
}
if (hasChildren) {
breadcrumb.children = menu.children?.map(item =>
transformBreadcrumbMenuToBreadcrumb(item as GlobalMenuOption, rootPath)
transformBreadcrumbMenuToBreadcrumb(item as App.GlobalMenuOption, rootPath)
);
}
return breadcrumb;

View File

@ -1,35 +0,0 @@
import type { Component } from 'vue';
import { BasicLayout, BlankLayout } from '@/layouts';
import { views } from '@/views';
type LayoutComponent = Record<EnumType.LayoutComponentName, () => Promise<Component>>;
/**
* 获取页面导入的vue文件(懒加载的方式)
* @param layoutType - 布局类型
*/
export function getLayoutComponent(layoutType: EnumType.LayoutComponentName) {
const layoutComponent: LayoutComponent = {
basic: BasicLayout,
blank: BlankLayout
};
return layoutComponent[layoutType];
}
/**
* 获取页面导入的vue文件(懒加载的方式)
* @param routeKey - 路由key
*/
export function getViewComponent(routeKey: AuthRoute.RouteKey) {
if (!views[routeKey]) {
window.console.error(`路由“${routeKey}”没有对应的组件文件!`);
}
return () => setViewComponentName(views[routeKey], routeKey) as Promise<Component>;
}
/** 给页面组件设置名称 */
async function setViewComponentName(asyncComponent: () => Promise<Component>, name: string) {
const component = (await asyncComponent()) as { default: Component };
Object.assign(component.default, { name });
return component;
}

View File

@ -1,6 +1,3 @@
import type { RouteRecordRaw } from 'vue-router';
import { getLayoutComponent, getViewComponent } from './component';
/**
* 获取所有固定路由的名称集合
* @param routes - 固定路由
@ -9,41 +6,30 @@ export function getConstantRouteNames(routes: AuthRoute.Route[]) {
return routes.map(route => getConstantRouteName(route)).flat(1);
}
/**
* 将权限路由转换成vue路由
* @param routes - 权限路由
* @description 所有多级路由都会被转换成二级路由
*/
export function transformAuthRoutesToVueRoutes(routes: AuthRoute.Route[]) {
return routes.map(route => transformAuthRouteToVueRoute(route)).flat(1);
}
/**
* 将权限路由转换成搜索的菜单数据
* @param routes - 权限路由
* @param treeMap
*/
export function transformAuthRoutesToSearchMenus(routes: AuthRoute.Route[], treeMap: AuthRoute.Route[] = []) {
export function transformAuthRouteToSearchMenus(routes: AuthRoute.Route[], treeMap: AuthRoute.Route[] = []) {
if (routes && routes.length === 0) return [];
return routes.reduce((acc, cur) => {
if (!cur.meta?.hide) {
acc.push(cur);
}
if (cur.children && cur.children.length > 0) {
transformAuthRoutesToSearchMenus(cur.children, treeMap);
transformAuthRouteToSearchMenus(cur.children, treeMap);
}
return acc;
}, treeMap);
}
/** 将路由名字转换成路由路径 */
export function transformRouteNameToRoutePath(
name: Exclude<AuthRoute.RouteKey, 'not-found-page'>
): AuthRoute.RoutePath {
export function transformRouteNameToRoutePath(name: Exclude<AuthRoute.AllRouteKey, 'not-found'>): AuthRoute.RoutePath {
const rootPath: AuthRoute.RoutePath = '/';
if (name === 'root') return rootPath;
const splitMark: AuthRoute.RouteSplitMark = '_';
const splitMark = '_';
const pathSplitMark = '/';
const path = name.split(splitMark).join(pathSplitMark);
@ -51,15 +37,13 @@ export function transformRouteNameToRoutePath(
}
/** 将路由路径转换成路由名字 */
export function transformRoutePathToRouteName(
path: Exclude<AuthRoute.RoutePath, '/not-found-page' | '/:pathMatch(.*)*'>
): AuthRoute.RouteKey {
export function transformRoutePathToRouteName<K extends AuthRoute.RoutePath>(path: K) {
if (path === '/') return 'root';
const pathSplitMark = '/';
const routeSplitMark: AuthRoute.RouteSplitMark = '_';
const routeSplitMark = '_';
const name = path.split(pathSplitMark).slice(1).join(routeSplitMark) as AuthRoute.RouteKey;
const name = path.split(pathSplitMark).slice(1).join(routeSplitMark) as AuthRoute.AllRouteKey;
return name;
}
@ -76,140 +60,6 @@ function getConstantRouteName(route: AuthRoute.Route) {
return names;
}
type ComponentAction = Record<AuthRoute.RouteComponent, () => void>;
/**
* 将单个权限路由转换成vue路由
* @param item - 单个权限路由
*/
export function transformAuthRouteToVueRoute(item: AuthRoute.Route) {
const resultRoute: RouteRecordRaw[] = [];
const itemRoute = { ...item } as RouteRecordRaw;
// 动态path
if (hasDynamicPath(item)) {
Object.assign(itemRoute, { path: item.meta.dynamicPath });
}
// 外链路由
if (hasHref(item)) {
Object.assign(itemRoute, { component: getViewComponent('not-found-page') });
}
// 路由组件
if (hasComponent(item)) {
const action: ComponentAction = {
basic() {
itemRoute.component = getLayoutComponent('basic');
},
blank() {
itemRoute.component = getLayoutComponent('blank');
},
multi() {
// 多级路由一定有子路由
if (hasChildren(item)) {
Object.assign(itemRoute, { meta: { ...itemRoute.meta, multi: true } });
delete itemRoute.component;
} else {
window.console.error('多级路由缺少子路由: ', item);
}
},
self() {
itemRoute.component = getViewComponent(item.name);
}
};
try {
if (item.component) {
action[item.component]();
} else {
window.console.error('路由组件解析失败: ', item);
}
} catch {
window.console.error('路由组件解析失败: ', item);
}
}
// 注意单独路由没有children
if (isSingleRoute(item)) {
if (hasChildren(item)) {
window.console.error('单独路由不应该有子路由: ', item);
}
// 捕获无效路由的需特殊处理
if (item.name === 'not-found-page') {
itemRoute.children = [
{
path: '',
name: item.name,
component: getViewComponent('not-found-page')
}
];
} else {
const parentPath = `${itemRoute.path}-parent` as AuthRoute.SingleRouteParentPath;
const layout = item.meta.singleLayout === 'basic' ? getLayoutComponent('basic') : getLayoutComponent('blank');
const parentRoute: RouteRecordRaw = {
path: parentPath,
component: layout,
redirect: item.path,
children: [itemRoute]
};
return [parentRoute];
}
}
// 子路由
if (hasChildren(item)) {
const children = (item.children as AuthRoute.Route[]).map(child => transformAuthRouteToVueRoute(child)).flat();
// 找出第一个不为多级路由中间级的子路由路径作为重定向路径
const redirectPath: AuthRoute.RoutePath = (children.find(v => !v.meta?.multi)?.path || '/') as AuthRoute.RoutePath;
if (redirectPath === '/') {
window.console.error('该多级路由没有有效的子路径', item);
}
if (item.component === 'multi') {
// 多级路由,将子路由提取出来变成同级
resultRoute.push(...children);
delete itemRoute.children;
} else {
itemRoute.children = children;
}
itemRoute.redirect = redirectPath;
}
resultRoute.push(itemRoute);
return resultRoute;
}
/**
* 是否有外链
* @param item - 权限路由
*/
function hasHref(item: AuthRoute.Route) {
return Boolean(item.meta.href);
}
/**
* 是否有动态路由path
* @param item - 权限路由
*/
function hasDynamicPath(item: AuthRoute.Route) {
return Boolean(item.meta.dynamicPath);
}
/**
* 是否有路由组件
* @param item - 权限路由
*/
function hasComponent(item: AuthRoute.Route) {
return Boolean(item.component);
}
/**
* 是否有子路由
* @param item - 权限路由
@ -217,11 +67,3 @@ function hasComponent(item: AuthRoute.Route) {
function hasChildren(item: AuthRoute.Route) {
return Boolean(item.children && item.children.length);
}
/**
* 是否是单层级路由
* @param item - 权限路由
*/
function isSingleRoute(item: AuthRoute.Route) {
return Boolean(item.meta.singleLayout);
}

View File

@ -7,10 +7,10 @@ function hideInMenu(route: AuthRoute.Route) {
/** 给菜单添加可选属性 */
function addPartialProps(config: {
menu: GlobalMenuOption;
menu: App.GlobalMenuOption;
icon?: string;
localIcon?: string;
children?: GlobalMenuOption[];
children?: App.GlobalMenuOption[];
}) {
const { iconRender } = useIconRender();
@ -36,16 +36,16 @@ function addPartialProps(config: {
* 将权限路由转换成菜单
* @param routes - 路由
*/
export function transformAuthRouteToMenu(routes: AuthRoute.Route[]): GlobalMenuOption[] {
const globalMenu: GlobalMenuOption[] = [];
export function transformAuthRouteToMenu(routes: AuthRoute.Route[]): App.GlobalMenuOption[] {
const globalMenu: App.GlobalMenuOption[] = [];
routes.forEach(route => {
const { name, path, meta } = route;
const routeName = name as string;
let menuChildren: GlobalMenuOption[] | undefined;
let menuChildren: App.GlobalMenuOption[] | undefined;
if (route.children) {
menuChildren = transformAuthRouteToMenu(route.children);
}
const menuItem: GlobalMenuOption = addPartialProps({
const menuItem: App.GlobalMenuOption = addPartialProps({
menu: {
key: routeName,
label: meta.title,
@ -70,18 +70,18 @@ export function transformAuthRouteToMenu(routes: AuthRoute.Route[]): GlobalMenuO
* @param activeKey - 当前路由的key
* @param menus - 菜单数据
*/
export function getActiveKeyPathsOfMenus(activeKey: string, menus: GlobalMenuOption[]) {
export function getActiveKeyPathsOfMenus(activeKey: string, menus: App.GlobalMenuOption[]) {
const keys = menus.map(menu => getActiveKeyPathsOfMenu(activeKey, menu)).flat(1);
return keys;
}
function getActiveKeyPathsOfMenu(activeKey: string, menu: GlobalMenuOption) {
function getActiveKeyPathsOfMenu(activeKey: string, menu: App.GlobalMenuOption) {
const keys: string[] = [];
if (activeKey.includes(menu.routeName)) {
keys.push(menu.routeName);
}
if (menu.children) {
keys.push(...menu.children.map(item => getActiveKeyPathsOfMenu(activeKey, item as GlobalMenuOption)).flat(1));
keys.push(...menu.children.map(item => getActiveKeyPathsOfMenu(activeKey, item as App.GlobalMenuOption)).flat(1));
}
return keys;
}

View File

@ -0,0 +1,214 @@
import type { RouteComponent, RouteRecordRaw } from 'vue-router';
import { BasicLayout, BlankLayout } from '@/layouts';
import { views } from '@/views';
import { isFunction } from '@/utils';
type Lazy<T> = () => Promise<T>;
type LayoutComponent = Record<EnumType.LayoutComponentName, Lazy<RouteComponent>>;
/**
* 获取布局的vue文件(懒加载的方式)
* @param layoutType - 布局类型
*/
export function getLayoutComponent(layoutType: EnumType.LayoutComponentName) {
const layoutComponent: LayoutComponent = {
basic: BasicLayout,
blank: BlankLayout
};
return layoutComponent[layoutType];
}
/**
* 获取页面导入的vue文件
* @param routeKey - 路由key
*/
export function getViewComponent(routeKey: AuthRoute.LastDegreeRouteKey) {
if (!views[routeKey]) {
throw new Error(`路由“${routeKey}”没有对应的组件文件!`);
}
return setViewComponentName(views[routeKey], routeKey);
}
interface ModuleComponent {
default: RouteComponent;
}
/** 给页面组件设置名称 */
function setViewComponentName(component: RouteComponent | Lazy<ModuleComponent>, name: string) {
if (isAsyncComponent(component)) {
return async () => {
const result = await component();
Object.assign(result.default, { name });
return result;
};
}
Object.assign(component, { name });
return component;
}
function isAsyncComponent(component: RouteComponent | Lazy<ModuleComponent>): component is Lazy<ModuleComponent> {
return isFunction(component);
}
/**
* 是否有外链
* @param item - 权限路由
*/
function hasHref(item: AuthRoute.Route) {
return Boolean(item.meta.href);
}
/**
* 是否有动态路由path
* @param item - 权限路由
*/
function hasDynamicPath(item: AuthRoute.Route) {
return Boolean(item.meta.dynamicPath);
}
/**
* 是否有路由组件
* @param item - 权限路由
*/
function hasComponent(item: AuthRoute.Route) {
return Boolean(item.component);
}
/**
* 是否有子路由
* @param item - 权限路由
*/
function hasChildren(item: AuthRoute.Route) {
return Boolean(item.children && item.children.length);
}
/**
* 是否是单层级路由
* @param item - 权限路由
*/
function isSingleRoute(item: AuthRoute.Route) {
return Boolean(item.meta.singleLayout);
}
/**
* 将权限路由转换成vue路由
* @param routes - 权限路由
* @description 所有多级路由都会被转换成二级路由
*/
export function transformAuthRouteToVueRoutes(routes: AuthRoute.Route[]) {
return routes.map(route => transformAuthRouteToVueRoute(route)).flat(1);
}
type ComponentAction = Record<AuthRoute.RouteComponentType, () => void>;
/**
* 将单个权限路由转换成vue路由
* @param item - 单个权限路由
*/
export function transformAuthRouteToVueRoute(item: AuthRoute.Route) {
const resultRoute: RouteRecordRaw[] = [];
const itemRoute = { ...item } as RouteRecordRaw;
// 动态path
if (hasDynamicPath(item)) {
Object.assign(itemRoute, { path: item.meta.dynamicPath });
}
// 外链路由
if (hasHref(item)) {
Object.assign(itemRoute, { component: getViewComponent('404') });
}
// 路由组件
if (hasComponent(item)) {
const action: ComponentAction = {
basic() {
itemRoute.component = getLayoutComponent('basic');
},
blank() {
itemRoute.component = getLayoutComponent('blank');
},
multi() {
// 多级路由一定有子路由
if (hasChildren(item)) {
Object.assign(itemRoute, { meta: { ...itemRoute.meta, multi: true } });
delete itemRoute.component;
} else {
window.console.error('多级路由缺少子路由: ', item);
}
},
self() {
itemRoute.component = getViewComponent(item.name as AuthRoute.LastDegreeRouteKey);
}
};
try {
if (item.component) {
action[item.component]();
} else {
window.console.error('路由组件解析失败: ', item);
}
} catch {
window.console.error('路由组件解析失败: ', item);
}
}
// 注意单独路由没有children
if (isSingleRoute(item)) {
if (hasChildren(item)) {
window.console.error('单独路由不应该有子路由: ', item);
}
// 捕获无效路由的需特殊处理
if (item.name === 'not-found') {
itemRoute.children = [
{
path: '',
name: item.name,
component: getViewComponent('not-found')
}
];
} else {
const parentPath = `${itemRoute.path}-parent` as AuthRouteUtils.SingleRouteKey;
const layout = item.meta.singleLayout === 'basic' ? getLayoutComponent('basic') : getLayoutComponent('blank');
const parentRoute: RouteRecordRaw = {
path: parentPath,
component: layout,
redirect: item.path,
children: [itemRoute]
};
return [parentRoute];
}
}
// 子路由
if (hasChildren(item)) {
const children = (item.children as AuthRoute.Route[]).map(child => transformAuthRouteToVueRoute(child)).flat();
// 找出第一个不为多级路由中间级的子路由路径作为重定向路径
const redirectPath = (children.find(v => !v.meta?.multi)?.path || '/') as AuthRoute.RoutePath;
if (redirectPath === '/') {
window.console.error('该多级路由没有有效的子路径', item);
}
if (item.component === 'multi') {
// 多级路由,将子路由提取出来变成同级
resultRoute.push(...children);
delete itemRoute.children;
} else {
itemRoute.children = children;
}
itemRoute.redirect = redirectPath;
}
resultRoute.push(itemRoute);
return resultRoute;
}