Skip to content

Commit 0cf09ba

Browse files
committed
feat(router): add sortRoutesByOrder function
1 parent 748cfa2 commit 0cf09ba

File tree

2 files changed

+21
-2
lines changed

2 files changed

+21
-2
lines changed

src/store/modules/route/index.ts

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import {
1818
getGlobalMenusByAuthRoutes,
1919
getSelectedMenuKeyPathByKey,
2020
isRouteExistByRouteName,
21+
sortRoutesByOrder,
2122
updateLocaleOfGlobalMenus
2223
} from './shared';
2324

@@ -185,11 +186,13 @@ export const useRouteStore = defineStore(SetupStoreId.Route, () => {
185186
* @param routes Auth routes
186187
*/
187188
function handleAuthRoutes(routes: ElegantConstRoute[]) {
188-
const vueRoutes = getAuthVueRoutes(routes);
189+
const sortRoutes = sortRoutesByOrder(routes);
190+
191+
const vueRoutes = getAuthVueRoutes(sortRoutes);
189192

190193
addRoutesToVueRouter(vueRoutes);
191194

192-
getGlobalMenus(routes);
195+
getGlobalMenus(sortRoutes);
193196

194197
getCacheRoutes(vueRoutes);
195198
}

src/store/modules/route/shared.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,22 @@ function filterAuthRouteByRoles(route: ElegantConstRoute, roles: string[]) {
4444
return hasPermission ? [filterRoute] : [];
4545
}
4646

47+
/**
48+
* Sort routes by order
49+
*
50+
* @param routes An array of routes
51+
* @returns A new array of routes sorted by order
52+
*
53+
* This function sorts the routes by their order property, which is a number. If the order property is missing or
54+
* invalid, it is treated as 0. The routes with lower order values are placed before the routes with higher order
55+
* values. The function also sorts the children routes recursively, if any.
56+
*/
57+
export const sortRoutesByOrder = (routes: ElegantConstRoute[]): ElegantConstRoute[] => {
58+
return routes
59+
.sort((next, prev) => (Number(next.meta?.order) || 0) - (Number(prev.meta?.order) || 0))
60+
.map(route => (route.children ? { ...route, children: sortRoutesByOrder(route.children) } : route));
61+
};
62+
4763
/**
4864
* Get global menus by auth routes
4965
*

0 commit comments

Comments
 (0)