refactor: ♻️ 动态路由加载代码优化方便理解
This commit is contained in:
@@ -15,7 +15,7 @@
|
|||||||
>
|
>
|
||||||
<!-- 菜单项 -->
|
<!-- 菜单项 -->
|
||||||
<SidebarMenuItem
|
<SidebarMenuItem
|
||||||
v-for="route in menuList"
|
v-for="route in data"
|
||||||
:key="route.path"
|
:key="route.path"
|
||||||
:item="route"
|
:item="route"
|
||||||
:base-path="resolveFullPath(route.path)"
|
:base-path="resolveFullPath(route.path)"
|
||||||
@@ -26,6 +26,7 @@
|
|||||||
<script lang="ts" setup>
|
<script lang="ts" setup>
|
||||||
import path from "path-browserify";
|
import path from "path-browserify";
|
||||||
import type { MenuInstance } from "element-plus";
|
import type { MenuInstance } from "element-plus";
|
||||||
|
import type { RouteRecordRaw } from "vue-router";
|
||||||
|
|
||||||
import { LayoutEnum } from "@/enums/LayoutEnum";
|
import { LayoutEnum } from "@/enums/LayoutEnum";
|
||||||
import { useSettingsStore, useAppStore } from "@/store";
|
import { useSettingsStore, useAppStore } from "@/store";
|
||||||
@@ -34,8 +35,8 @@ import { isExternal } from "@/utils/index";
|
|||||||
import variables from "@/styles/variables.module.scss";
|
import variables from "@/styles/variables.module.scss";
|
||||||
|
|
||||||
const props = defineProps({
|
const props = defineProps({
|
||||||
menuList: {
|
data: {
|
||||||
type: Array<any>,
|
type: Array<RouteRecordRaw>,
|
||||||
required: true,
|
required: true,
|
||||||
default: () => [],
|
default: () => [],
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -28,17 +28,11 @@
|
|||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script lang="ts" setup>
|
<script lang="ts" setup>
|
||||||
/**
|
|
||||||
* 导入模块:先外部库,再内部模块,最后导入样式和工具类
|
|
||||||
*/
|
|
||||||
import { LocationQueryRaw, RouteRecordRaw } from "vue-router";
|
import { LocationQueryRaw, RouteRecordRaw } from "vue-router";
|
||||||
import { usePermissionStore, useAppStore } from "@/store";
|
import { usePermissionStore, useAppStore } from "@/store";
|
||||||
import { translateRouteTitle } from "@/utils/i18n";
|
import { translateRouteTitle } from "@/utils/i18n";
|
||||||
import variables from "@/styles/variables.module.scss";
|
import variables from "@/styles/variables.module.scss";
|
||||||
|
|
||||||
/**
|
|
||||||
* 定义状态:先定义 reactive、ref 或 computed 状态
|
|
||||||
*/
|
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const appStore = useAppStore();
|
const appStore = useAppStore();
|
||||||
const permissionStore = usePermissionStore();
|
const permissionStore = usePermissionStore();
|
||||||
@@ -64,8 +58,8 @@ appStore.activeTopMenu(activeTopMenuPath);
|
|||||||
*/
|
*/
|
||||||
const handleMenuSelect = (routePath: string) => {
|
const handleMenuSelect = (routePath: string) => {
|
||||||
appStore.activeTopMenu(routePath); // 设置激活的顶部菜单
|
appStore.activeTopMenu(routePath); // 设置激活的顶部菜单
|
||||||
permissionStore.setMixLeftMenus(routePath); // 更新左侧菜单
|
permissionStore.setMixedLayoutLeftRoutes(routePath); // 更新左侧菜单
|
||||||
navigateToFirstLeftMenu(permissionStore.mixLeftMenus); // 跳转到左侧第一个菜单
|
navigateToFirstLeftMenu(permissionStore.mixedLayoutLeftRoutes); // 跳转到左侧第一个菜单
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -1,20 +1,20 @@
|
|||||||
<template>
|
<template>
|
||||||
<div :class="{ 'has-logo': sidebarLogo }">
|
<div :class="{ 'has-logo': sidebarLogo }">
|
||||||
<!-- 混合布局顶部 -->
|
<!-- 混合 -->
|
||||||
<div v-if="isMixLayout" class="flex w-full">
|
<div v-if="isMixLayout" class="flex w-full">
|
||||||
<SidebarLogo v-if="sidebarLogo" :collapse="isSidebarCollapsed" />
|
<SidebarLogo v-if="sidebarLogo" :collapse="isSidebarCollapsed" />
|
||||||
<SidebarMixTopMenu class="flex-1" />
|
<SidebarMixTopMenu class="flex-1" />
|
||||||
<NavbarRight />
|
<NavbarRight />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- 顶部布局顶部 || 左侧布局左侧 -->
|
<!-- 顶部 || 左侧 -->
|
||||||
<template v-else>
|
<template v-else>
|
||||||
<SidebarLogo v-if="sidebarLogo" :collapse="isSidebarCollapsed" />
|
<SidebarLogo v-if="sidebarLogo" :collapse="isSidebarCollapsed" />
|
||||||
<el-scrollbar>
|
<el-scrollbar>
|
||||||
<SidebarMenu :menu-list="permissionStore.routes" base-path="" />
|
<SidebarMenu :data="permissionStore.routes" base-path="" />
|
||||||
</el-scrollbar>
|
</el-scrollbar>
|
||||||
|
|
||||||
<!-- 顶部布局导航 -->
|
<!-- 顶部导航 -->
|
||||||
<NavbarRight v-if="isTopLayout" />
|
<NavbarRight v-if="isTopLayout" />
|
||||||
</template>
|
</template>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -14,7 +14,7 @@
|
|||||||
<div v-if="layout === LayoutEnum.MIX" class="mix-container">
|
<div v-if="layout === LayoutEnum.MIX" class="mix-container">
|
||||||
<div class="mix-container-sidebar">
|
<div class="mix-container-sidebar">
|
||||||
<el-scrollbar>
|
<el-scrollbar>
|
||||||
<SidebarMenu :menu-list="mixLeftMenus" :base-path="activeTopMenuPath" />
|
<SidebarMenu :data="mixedLayoutLeftRoutes" :base-path="activeTopMenuPath" />
|
||||||
</el-scrollbar>
|
</el-scrollbar>
|
||||||
<div class="sidebar-toggle">
|
<div class="sidebar-toggle">
|
||||||
<hamburger :is-active="appStore.sidebar.opened" @toggle-click="toggleSidebar" />
|
<hamburger :is-active="appStore.sidebar.opened" @toggle-click="toggleSidebar" />
|
||||||
@@ -65,12 +65,12 @@ const isOpenSidebar = computed(() => appStore.sidebar.opened);
|
|||||||
const showTagsView = computed(() => settingsStore.tagsView); // 是否显示tagsView
|
const showTagsView = computed(() => settingsStore.tagsView); // 是否显示tagsView
|
||||||
const layout = computed(() => settingsStore.layout); // 布局模式 left top mix
|
const layout = computed(() => settingsStore.layout); // 布局模式 left top mix
|
||||||
const activeTopMenuPath = computed(() => appStore.activeTopMenuPath); // 顶部菜单激活path
|
const activeTopMenuPath = computed(() => appStore.activeTopMenuPath); // 顶部菜单激活path
|
||||||
const mixLeftMenus = computed(() => permissionStore.mixLeftMenus); // 混合布局左侧菜单
|
const mixedLayoutLeftRoutes = computed(() => permissionStore.mixedLayoutLeftRoutes); // 混合布局左侧菜单
|
||||||
|
|
||||||
watch(
|
watch(
|
||||||
() => activeTopMenuPath.value,
|
() => activeTopMenuPath.value,
|
||||||
(newVal: string) => {
|
(newVal: string) => {
|
||||||
permissionStore.setMixLeftMenus(newVal);
|
permissionStore.setMixedLayoutLeftRoutes(newVal);
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
deep: true,
|
deep: true,
|
||||||
@@ -280,8 +280,8 @@ watch(route, () => {
|
|||||||
&.mobile {
|
&.mobile {
|
||||||
.sidebar-container {
|
.sidebar-container {
|
||||||
pointer-events: none;
|
pointer-events: none;
|
||||||
transition-duration: 0.3s;
|
|
||||||
transform: translate3d(-210px, 0, 0);
|
transform: translate3d(-210px, 0, 0);
|
||||||
|
transition-duration: 0.3s;
|
||||||
}
|
}
|
||||||
|
|
||||||
.main-container {
|
.main-container {
|
||||||
|
|||||||
@@ -8,22 +8,24 @@ const modules = import.meta.glob("../../views/**/**.vue");
|
|||||||
const Layout = () => import("@/layout/index.vue");
|
const Layout = () => import("@/layout/index.vue");
|
||||||
|
|
||||||
export const usePermissionStore = defineStore("permission", () => {
|
export const usePermissionStore = defineStore("permission", () => {
|
||||||
// 所有路由,包括静态和动态路由
|
// 储所有路由,包括静态路由和动态路由
|
||||||
const routes = ref<RouteRecordRaw[]>([]);
|
const routes = ref<RouteRecordRaw[]>([]);
|
||||||
// 混合模式左侧菜单
|
// 混合模式左侧菜单路由
|
||||||
const mixLeftMenus = ref<RouteRecordRaw[]>([]);
|
const mixedLayoutLeftRoutes = ref<RouteRecordRaw[]>([]);
|
||||||
// 路由是否已加载
|
// 路由是否加载完成
|
||||||
const isRoutesLoaded = ref(false);
|
const isRoutesLoaded = ref(false);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 生成动态路由
|
* 获取后台动态路由数据,解析并注册到全局路由
|
||||||
|
*
|
||||||
|
* @returns Promise<RouteRecordRaw[]> 解析后的动态路由列表
|
||||||
*/
|
*/
|
||||||
function generateRoutes() {
|
function generateRoutes() {
|
||||||
return new Promise<RouteRecordRaw[]>((resolve, reject) => {
|
return new Promise<RouteRecordRaw[]>((resolve, reject) => {
|
||||||
MenuAPI.getRoutes()
|
MenuAPI.getRoutes()
|
||||||
.then((data) => {
|
.then((data) => {
|
||||||
const dynamicRoutes = transformRoutes(data);
|
const dynamicRoutes = parseDynamicRoutes(data);
|
||||||
routes.value = constantRoutes.concat(dynamicRoutes);
|
routes.value = [...constantRoutes, ...dynamicRoutes];
|
||||||
isRoutesLoaded.value = true;
|
isRoutesLoaded.value = true;
|
||||||
resolve(dynamicRoutes);
|
resolve(dynamicRoutes);
|
||||||
})
|
})
|
||||||
@@ -34,14 +36,14 @@ export const usePermissionStore = defineStore("permission", () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 混合模式菜单下根据顶部菜单路径设置左侧菜单
|
* 根据父菜单路径设置混合模式左侧菜单
|
||||||
*
|
*
|
||||||
* @param topMenuPath - 顶部菜单路径
|
* @param parentPath 父菜单的路径,用于查找对应的菜单项
|
||||||
*/
|
*/
|
||||||
const setMixLeftMenus = (topMenuPath: string) => {
|
const setMixedLayoutLeftRoutes = (parentPath: string) => {
|
||||||
const matchedItem = routes.value.find((item) => item.path === topMenuPath);
|
const matchedItem = routes.value.find((item) => item.path === parentPath);
|
||||||
if (matchedItem && matchedItem.children) {
|
if (matchedItem && matchedItem.children) {
|
||||||
mixLeftMenus.value = matchedItem.children;
|
mixedLayoutLeftRoutes.value = matchedItem.children;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -49,59 +51,62 @@ export const usePermissionStore = defineStore("permission", () => {
|
|||||||
* 重置路由
|
* 重置路由
|
||||||
*/
|
*/
|
||||||
const resetRouter = () => {
|
const resetRouter = () => {
|
||||||
// 删除动态路由,保留静态路由
|
// 清空本地存储的路由和菜单数据
|
||||||
routes.value.forEach((route) => {
|
routes.value = [];
|
||||||
if (route.name && !constantRoutes.find((r) => r.name === route.name)) {
|
mixedLayoutLeftRoutes.value = [];
|
||||||
// 从 router 实例中移除动态路由
|
// 从 Vue Router 中移除所有动态注册的路由
|
||||||
|
router.getRoutes().forEach((route) => {
|
||||||
|
if (route.name) {
|
||||||
router.removeRoute(route.name);
|
router.removeRoute(route.name);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
routes.value = [];
|
|
||||||
mixLeftMenus.value = [];
|
|
||||||
isRoutesLoaded.value = false;
|
isRoutesLoaded.value = false;
|
||||||
};
|
};
|
||||||
|
|
||||||
return {
|
return {
|
||||||
routes,
|
routes,
|
||||||
generateRoutes,
|
mixedLayoutLeftRoutes,
|
||||||
mixLeftMenus,
|
|
||||||
setMixLeftMenus,
|
|
||||||
isRoutesLoaded,
|
isRoutesLoaded,
|
||||||
|
generateRoutes,
|
||||||
|
setMixedLayoutLeftRoutes,
|
||||||
resetRouter,
|
resetRouter,
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 转换路由数据为组件
|
* 解析后端返回的路由数据并转换为 Vue Router 兼容的路由配置
|
||||||
|
*
|
||||||
|
* 1. 遍历 `rawRoutes` 并转换为 `RouteRecordRaw` 格式。
|
||||||
|
* 2. 若 `component` 为 `"Layout"`,则替换为 `Layout` 组件。
|
||||||
|
* 3. 若 `component` 为字符串路径,则动态加载对应的 Vue 组件,找不到则默认 `404.vue`。
|
||||||
|
* 4. 递归解析 `children`,确保子路由也被正确转换。
|
||||||
|
*
|
||||||
|
* @param rawRoutes 后端返回的原始路由数据
|
||||||
|
* @returns 解析后的路由配置数组
|
||||||
*/
|
*/
|
||||||
const transformRoutes = (routes: RouteVO[]) => {
|
const parseDynamicRoutes = (rawRoutes: RouteVO[]): RouteRecordRaw[] => {
|
||||||
const asyncRoutes: RouteRecordRaw[] = [];
|
const parsedRoutes: RouteRecordRaw[] = [];
|
||||||
routes.forEach((route) => {
|
|
||||||
const tmpRoute = { ...route } as RouteRecordRaw;
|
rawRoutes.forEach((route) => {
|
||||||
// 顶级目录,替换为 Layout 组件
|
const normalizedRoute = { ...route } as RouteRecordRaw;
|
||||||
if (tmpRoute.component?.toString() == "Layout") {
|
|
||||||
tmpRoute.component = Layout;
|
// 处理组件路径
|
||||||
} else {
|
normalizedRoute.component =
|
||||||
// 其他菜单,根据组件路径动态加载组件
|
normalizedRoute.component?.toString() === "Layout"
|
||||||
const component = modules[`../../views/${tmpRoute.component}.vue`];
|
? Layout
|
||||||
if (component) {
|
: modules[`../../views/${normalizedRoute.component}.vue`] ||
|
||||||
tmpRoute.component = component;
|
modules["../../views/error-page/404.vue"];
|
||||||
} else {
|
|
||||||
tmpRoute.component = modules["../../views/error-page/404.vue"];
|
// 递归解析子路由
|
||||||
}
|
if (normalizedRoute.children) {
|
||||||
|
normalizedRoute.children = parseDynamicRoutes(route.children);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (tmpRoute.children) {
|
parsedRoutes.push(normalizedRoute);
|
||||||
tmpRoute.children = transformRoutes(route.children);
|
|
||||||
}
|
|
||||||
|
|
||||||
asyncRoutes.push(tmpRoute);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
return asyncRoutes;
|
return parsedRoutes;
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 在组件外使用 Pinia store 实例 @see https://pinia.vuejs.org/core-concepts/outside-component-usage.html
|
* 在组件外使用 Pinia store 实例 @see https://pinia.vuejs.org/core-concepts/outside-component-usage.html
|
||||||
*/
|
*/
|
||||||
|
|||||||
Reference in New Issue
Block a user