Browse Source

chore: 优化菜单数据转换逻辑

lujialiang 3 weeks ago
parent
commit
655f247bd6
1 changed files with 41 additions and 20 deletions
  1. 41 20
      src/store/modules/route/custom.ts

+ 41 - 20
src/store/modules/route/custom.ts

@@ -11,34 +11,52 @@ interface DataItem {
   visible: string;
 }
 
-function replacePath(val: string) {
-  return val.slice(1).replace('/index', '').replace('/', '_');
+function pathToArray(path: string) {
+  return path.split('/').filter(e => e);
 }
-function getTransComponent(item: DataItem, level: number): string {
-  const { component: name, children } = item;
+
+function getLastPath(path: string) {
+  const result = pathToArray(path);
+  if (result.length) {
+    return `/${result.pop()}`;
+  }
+  return '';
+}
+
+function getTransComponentName(path: string) {
+  return pathToArray(path).join('_');
+}
+
+function getTransComponent(path: string, level: number, item: DataItem) {
+  const { children } = item;
   let isChildren = true;
   if (!children || children?.length === 0) {
     isChildren = false;
   }
-  if (level === 0 && !isChildren) {
-    return `layout.base$view.${replacePath(name)}`;
-  } else if (name === 'Layout') {
-    return 'layout.base';
+  const name = getTransComponentName(path);
+  if (level === 0) {
+    if (!isChildren) {
+      return `layout.base$view.${name}`;
+    }
+    return `layout.base`;
   }
-  const newVal = replacePath(name);
-  return `view.${newVal}`;
-}
-function getTransComponentName(val: string) {
-  const newVal = replacePath(val);
-  return newVal;
+  if (level === 1) {
+    if (!isChildren) {
+      return `view.${name}`;
+    }
+    return '';
+  }
+  return `view.${name}`;
 }
 
-function transData(menus: DataItem[], level: number = 0): ElegantConstRoute[] {
+function transData(menus: DataItem[], level: number = 0, basePath: string = ''): ElegantConstRoute[] {
   return menus.map(item => {
+    const itemPath = getLastPath(item.path);
+    const fullPath = basePath ? `${basePath}${itemPath}` : itemPath;
     const obj: ElegantConstRoute = {
-      name: getTransComponentName(item.path),
-      path: item.path,
-      component: getTransComponent(item, level),
+      name: getTransComponentName(fullPath),
+      path: fullPath,
+      component: getTransComponent(fullPath, level, item),
       meta: {
         title: item.title,
         order: item.sort,
@@ -49,7 +67,7 @@ function transData(menus: DataItem[], level: number = 0): ElegantConstRoute[] {
       children: []
     };
     if (Array.isArray(item.children)) {
-      obj.children = transData(item.children, level + 1);
+      obj.children = transData(item.children, level + 1, fullPath);
     }
     return obj;
   });
@@ -59,5 +77,8 @@ export function transformToTargetData(data: DataItem[]): {
   routes: ElegantConstRoute[];
   home: LastLevelRouteKey;
 } {
-  return { routes: transData(data), home: 'admin_sys-user' };
+  return {
+    routes: transData(data),
+    home: 'admin_sys-user'
+  };
 }