From 0cf09baef846bdbc6eb6c54481b994d831ea7004 Mon Sep 17 00:00:00 2001 From: Azir-11 <2075125282@qq.com> Date: Fri, 12 Jan 2024 02:51:39 +0800 Subject: [PATCH] feat(router): add sortRoutesByOrder function --- src/store/modules/route/index.ts | 7 +++++-- src/store/modules/route/shared.ts | 16 ++++++++++++++++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/src/store/modules/route/index.ts b/src/store/modules/route/index.ts index bb95af82..79fd5d3b 100644 --- a/src/store/modules/route/index.ts +++ b/src/store/modules/route/index.ts @@ -18,6 +18,7 @@ import { getGlobalMenusByAuthRoutes, getSelectedMenuKeyPathByKey, isRouteExistByRouteName, + sortRoutesByOrder, updateLocaleOfGlobalMenus } from './shared'; @@ -185,11 +186,13 @@ export const useRouteStore = defineStore(SetupStoreId.Route, () => { * @param routes Auth routes */ function handleAuthRoutes(routes: ElegantConstRoute[]) { - const vueRoutes = getAuthVueRoutes(routes); + const sortRoutes = sortRoutesByOrder(routes); + + const vueRoutes = getAuthVueRoutes(sortRoutes); addRoutesToVueRouter(vueRoutes); - getGlobalMenus(routes); + getGlobalMenus(sortRoutes); getCacheRoutes(vueRoutes); } diff --git a/src/store/modules/route/shared.ts b/src/store/modules/route/shared.ts index 82d44cfc..f4c6eed8 100644 --- a/src/store/modules/route/shared.ts +++ b/src/store/modules/route/shared.ts @@ -44,6 +44,22 @@ function filterAuthRouteByRoles(route: ElegantConstRoute, roles: string[]) { return hasPermission ? [filterRoute] : []; } +/** + * Sort routes by order + * + * @param routes An array of routes + * @returns A new array of routes sorted by order + * + * This function sorts the routes by their order property, which is a number. If the order property is missing or + * invalid, it is treated as 0. The routes with lower order values are placed before the routes with higher order + * values. The function also sorts the children routes recursively, if any. + */ +export const sortRoutesByOrder = (routes: ElegantConstRoute[]): ElegantConstRoute[] => { + return routes + .sort((next, prev) => (Number(next.meta?.order) || 0) - (Number(prev.meta?.order) || 0)) + .map(route => (route.children ? { ...route, children: sortRoutesByOrder(route.children) } : route)); +}; + /** * Get global menus by auth routes *