Merge branch 'fork/bnuephjx/refactor/router-redirect'

This commit is contained in:
金毛88
2026-07-01 13:31:27 +08:00
23 changed files with 189 additions and 176 deletions

View File

@@ -79,16 +79,22 @@ function filterTree<T extends Record<string, any>>(
*/
function mapTree<T, V extends Record<string, any>>(
tree: T[],
mapper: (node: T) => V,
mapper: (node: T, parent: null | V) => V,
options?: TreeConfigOptions,
parent: null | V = null,
): V[] {
const { childProps } = options || {
childProps: 'children',
};
return tree.map((node) => {
const mapperNode: Record<string, any> = mapper(node);
const mapperNode: Record<string, any> = mapper(node, parent as null | V);
if (mapperNode[childProps]) {
mapperNode[childProps] = mapTree(mapperNode[childProps], mapper, options);
mapperNode[childProps] = mapTree(
mapperNode[childProps],
mapper,
options,
mapperNode as V,
);
}
return mapperNode as V;
});

View File

@@ -115,7 +115,7 @@ async function generateRoutes(
* 1. 对未添加redirect的路由添加redirect
* 2. 将懒加载的组件名称修改为当前路由的名称如果启用了keep-alive的话
*/
resultRoutes = mapTree(resultRoutes, (route) => {
resultRoutes = mapTree(resultRoutes, (route, parent) => {
// 重新包装component使用与路由名称相同的name以支持keep-alive的条件缓存。
if (
route.meta?.keepAlive &&
@@ -144,12 +144,19 @@ async function generateRoutes(
}
const firstChild = route.children[0];
// 如果子路由不是以/开头,则直接返回,这种情况需要计算全部父级的path才能得出正确的path这里不做处理
if (!firstChild?.path || !firstChild.path.startsWith('/')) {
if (!firstChild?.path || firstChild.path.startsWith('/')) {
return route;
}
route.redirect = firstChild.path;
if (parent && parent.redirect) {
const parentSplit = (parent.redirect as string).split('/');
parentSplit.splice(-1, 2, route.path, firstChild.path);
const redirectPath = parentSplit.join('/');
route.redirect = redirectPath;
} else {
route.redirect = `${route.path}/${firstChild.path}`;
}
return route;
});