@@ -15,13 +15,65 @@ Nprogress.configure({
1515// 白名单路由
1616const WHITE_LIST = [ 'Login' , 'Init' ]
1717
18+ function isExternalUrl ( val ) {
19+ return typeof val === 'string' && / ^ ( h t t p s ? : ) ? \/ \/ / . test ( val )
20+ }
21+
22+ // 将 n 级菜单扁平化为:一级 layout + 二级页面组件
23+ function addRouteByChildren ( route , segments = [ ] ) {
24+ // 跳过外链根节点
25+ if ( isExternalUrl ( route ?. path ) || isExternalUrl ( route ?. name ) || isExternalUrl ( route ?. component ) ) {
26+ return
27+ }
28+
29+ // 顶层 layout 仅用于承载,不参与路径拼接
30+ if ( route ?. name === 'layout' ) {
31+ route . children ?. forEach ( ( child ) => addRouteByChildren ( child , [ ] ) )
32+ return
33+ }
34+
35+ // 还有子节点,继续向下收集路径片段(忽略外链片段)
36+ if ( route ?. children && route . children . length ) {
37+ const nextSegments = isExternalUrl ( route . path ) ? segments : [ ...segments , route . path ]
38+ route . children . forEach ( ( child ) => addRouteByChildren ( child , nextSegments ) )
39+ return
40+ }
41+
42+ // 叶子节点:注册为 layout 的二级子路由
43+ const fullPath = [ ...segments , route . path ] . filter ( Boolean ) . join ( '/' )
44+ const newRoute = { ...route , path : fullPath }
45+ delete newRoute . children
46+ delete newRoute . parent
47+ // 子路由使用相对路径,避免 /layout/layout/... 的问题
48+ newRoute . path = newRoute . path . replace ( / ^ \/ + / , '' )
49+
50+ router . addRoute ( 'layout' , newRoute )
51+ }
52+
1853// 处理路由加载
1954const setupRouter = async ( userStore ) => {
2055 try {
2156 const routerStore = useRouterStore ( )
2257 await Promise . all ( [ routerStore . SetAsyncRouter ( ) , userStore . GetUserInfo ( ) ] )
2358
24- routerStore . asyncRouters . forEach ( ( route ) => router . addRoute ( route ) )
59+ // 确保先注册父级 layout
60+ const baseRouters = routerStore . asyncRouters || [ ]
61+ const layoutRoute = baseRouters [ 0 ]
62+ if ( layoutRoute ?. name === 'layout' && ! router . hasRoute ( 'layout' ) ) {
63+ router . addRoute ( layoutRoute )
64+ }
65+
66+ // 扁平化:将 layout.children 与其余顶层异步路由一并作为二级子路由注册到 layout 下
67+ const toRegister = [ ]
68+ if ( layoutRoute ?. children ?. length ) {
69+ toRegister . push ( ...layoutRoute . children )
70+ }
71+ if ( baseRouters . length > 1 ) {
72+ baseRouters . slice ( 1 ) . forEach ( ( r ) => {
73+ if ( r ?. name !== 'layout' ) toRegister . push ( r )
74+ } )
75+ }
76+ toRegister . forEach ( ( r ) => addRouteByChildren ( r , [ ] ) )
2577 return true
2678 } catch ( error ) {
2779 console . error ( 'Setup router failed:' , error )
0 commit comments