From 8102c8a9242ee176571a2c551ff8d1d5dd100781 Mon Sep 17 00:00:00 2001 From: chenghongxing <1126263215@qq.com> Date: Thu, 3 Sep 2020 18:24:28 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20add=20deep=20merge=20routes=20function?= =?UTF-8?q?=20for=20routerUtil.js;=20:star:=20=E6=96=B0=E5=A2=9E=EF=BC=9Ar?= =?UTF-8?q?outerUtil.js=20=E5=B7=A5=E5=85=B7=E6=96=B0=E5=A2=9E=E6=B7=B1?= =?UTF-8?q?=E5=BA=A6=E5=90=88=E5=B9=B6=E8=B7=AF=E7=94=B1=E6=96=B9=E6=B3=95?= =?UTF-8?q?=EF=BC=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/utils/routerUtil.js | 41 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 40 insertions(+), 1 deletion(-) diff --git a/src/utils/routerUtil.js b/src/utils/routerUtil.js index 68416ea..dfab740 100644 --- a/src/utils/routerUtil.js +++ b/src/utils/routerUtil.js @@ -1,6 +1,7 @@ import routerMap from '@/router/async/router.map' import {mergeI18nFromRoutes} from '@/utils/i18n' import Router from 'vue-router' +import deepMerge from 'deepmerge' /** * 根据 路由配置 和 路由组件注册 解析路由 @@ -95,6 +96,44 @@ function mergeRoutes(target, source) { return Object.values(routesMap) } +/** + * 深度合并路由 + * @param target {Route[]} + * @param source {Route[]} + * @returns {Route[]} + */ +function deepMergeRoutes(target, source) { + // 映射路由数组 + const mapRoutes = routes => { + const routesMap = {} + routes.forEach(item => { + routesMap[item.path] = { + ...item, + children: item.children ? mapRoutes(item.children) : undefined + } + }) + return routesMap + } + const tarMap = mapRoutes(target) + const srcMap = mapRoutes(source) + + // 合并路由 + const merge = deepMerge(tarMap, srcMap) + + // 转换为 routes 数组 + const parseRoutesMap = routesMap => { + return Object.values(routesMap).map(item => { + if (item.children) { + item.children = parseRoutesMap(item.children) + } else { + delete item.children + } + return item + }) + } + return parseRoutesMap(merge) +} + /** * 格式化路由的权限配置 * @param routes 路由 @@ -164,4 +203,4 @@ function loadGuards(guards, options) { }) } -export {parseRoutes, loadRoutes, formatAuthority, getI18nKey, loadGuards} +export {parseRoutes, loadRoutes, formatAuthority, getI18nKey, loadGuards, deepMergeRoutes}