Commit 23711638 by Lin

feat: 动态路由菜单配置/删除冗余代码

1 parent c9f77efd
Showing 22 changed files with 584 additions and 215 deletions
...@@ -70,7 +70,6 @@ async function render(props: QiankunProps = {}) { ...@@ -70,7 +70,6 @@ async function render(props: QiankunProps = {}) {
* 直接访问子应用时,不是通过基座加载 * 直接访问子应用时,不是通过基座加载
*/ */
if (!qiankunWindow.__POWERED_BY_QIANKUN__) { if (!qiankunWindow.__POWERED_BY_QIANKUN__) {
console.log('独立运行模式');
render(); render();
} }
...@@ -79,7 +78,7 @@ if (!qiankunWindow.__POWERED_BY_QIANKUN__) { ...@@ -79,7 +78,7 @@ if (!qiankunWindow.__POWERED_BY_QIANKUN__) {
* 只会在微应用初始化的时候调用一次,下次微应用重新进入时会直接调用 mount 钩子 * 只会在微应用初始化的时候调用一次,下次微应用重新进入时会直接调用 mount 钩子
*/ */
export async function bootstrap() { export async function bootstrap() {
console.log('[Vue3 微应用] bootstrap'); console.log('[Vue3 微应用钩子] bootstrap');
} }
/** /**
...@@ -87,7 +86,7 @@ export async function bootstrap() { ...@@ -87,7 +86,7 @@ export async function bootstrap() {
* 应用每次进入都会调用 mount 方法,通常在这里触发应用的渲染方法 * 应用每次进入都会调用 mount 方法,通常在这里触发应用的渲染方法
*/ */
export async function mount(props: QiankunProps) { export async function mount(props: QiankunProps) {
console.log('Vue3 微应用 mount', props); console.log('Vue3 微应用钩子 mount', props);
render(props); render(props);
} }
......
...@@ -71,7 +71,6 @@ class SubAppCommunicationManager { ...@@ -71,7 +71,6 @@ class SubAppCommunicationManager {
} }
this.listeners = []; this.listeners = [];
this.props = null; this.props = null;
console.log('[子应用通信] 通信管理器已销毁');
} }
/** /**
...@@ -92,7 +91,6 @@ class SubAppCommunicationManager { ...@@ -92,7 +91,6 @@ class SubAppCommunicationManager {
if (props.onGlobalStateChange) { if (props.onGlobalStateChange) {
const unsubscribeFn = props.onGlobalStateChange( const unsubscribeFn = props.onGlobalStateChange(
(state: GlobalState, prev: GlobalState) => { (state: GlobalState, prev: GlobalState) => {
console.log('[子应用通信] 全局状态变化:', state, prev);
// 缓存当前状态 // 缓存当前状态
this.currentState = state; this.currentState = state;
...@@ -123,7 +121,6 @@ class SubAppCommunicationManager { ...@@ -123,7 +121,6 @@ class SubAppCommunicationManager {
// 如果已经有缓存的状态,立即调用一次回调 // 如果已经有缓存的状态,立即调用一次回调
if (this.currentState) { if (this.currentState) {
console.log('[子应用通信] 立即触发回调,使用缓存的全局状态');
callback(this.currentState, {} as GlobalState); callback(this.currentState, {} as GlobalState);
} }
...@@ -141,7 +138,6 @@ class SubAppCommunicationManager { ...@@ -141,7 +138,6 @@ class SubAppCommunicationManager {
*/ */
sendNotification(notification: Omit<Notification, 'id' | 'timestamp'>) { sendNotification(notification: Omit<Notification, 'id' | 'timestamp'>) {
if (!this.props?.setGlobalState) { if (!this.props?.setGlobalState) {
console.warn('[子应用通信] 无法发送通知,setGlobalState 方法不可用');
return; return;
} }
...@@ -169,10 +165,7 @@ class SubAppCommunicationManager { ...@@ -169,10 +165,7 @@ class SubAppCommunicationManager {
setGlobalState(state: Partial<GlobalState>) { setGlobalState(state: Partial<GlobalState>) {
if (this.props?.setGlobalState) { if (this.props?.setGlobalState) {
this.props.setGlobalState(state); this.props.setGlobalState(state);
console.log('[子应用通信] 全局状态已更新:', state); }
} else {
console.warn('[子应用通信] setGlobalState 方法不可用');
}
} }
} }
......
...@@ -249,7 +249,6 @@ const removeFile = () => { ...@@ -249,7 +249,6 @@ const removeFile = () => {
} }
const save = () => { const save = () => {
console.log('保存数据:', formData)
// TODO: 调用 API 保存数据 // TODO: 调用 API 保存数据
// if (isEditMode.value) { // if (isEditMode.value) {
...@@ -267,7 +266,6 @@ const save = () => { ...@@ -267,7 +266,6 @@ const save = () => {
} }
const cancel = () => { const cancel = () => {
console.log('取消操作')
} }
</script> </script>
......
...@@ -81,7 +81,6 @@ const sendNotification = async () => { ...@@ -81,7 +81,6 @@ const sendNotification = async () => {
notificationForm.title = ''; notificationForm.title = '';
notificationForm.message = ''; notificationForm.message = '';
} catch (error) { } catch (error) {
console.error('发送通知失败:', error);
addLog('error', '发送通知失败'); addLog('error', '发送通知失败');
} }
}; };
...@@ -138,7 +137,6 @@ onMounted(async () => { ...@@ -138,7 +137,6 @@ onMounted(async () => {
addLog('init', '通信管理器初始化成功'); addLog('init', '通信管理器初始化成功');
} catch (error) { } catch (error) {
console.error('初始化通信失败:', error);
addLog('error', '通信管理器初始化失败'); addLog('error', '通信管理器初始化失败');
} }
} }
......
...@@ -36,7 +36,6 @@ const defaultSettings: Settings = { ...@@ -36,7 +36,6 @@ const defaultSettings: Settings = {
const settings = reactive<Settings>({ ...defaultSettings }); const settings = reactive<Settings>({ ...defaultSettings });
const saveSettings = () => { const saveSettings = () => {
console.log('保存设置:', settings);
alert('设置已保存!'); alert('设置已保存!');
}; };
......
...@@ -52,7 +52,6 @@ const addUser = () => { ...@@ -52,7 +52,6 @@ const addUser = () => {
}; };
const editUser = (user: User) => { const editUser = (user: User) => {
console.log('编辑用户:', user);
alert(`编辑用户: ${user.name}`); alert(`编辑用户: ${user.name}`);
}; };
......
...@@ -128,13 +128,7 @@ const handleLogin = async () => { ...@@ -128,13 +128,7 @@ const handleLogin = async () => {
```vue ```vue
<script setup lang="ts"> <script setup lang="ts">
import { useUserStore } from '@/stores'; import { useUserStore } from '@/stores';
const userStore = useUserStore(); const userStore = useUserStore();
// 获取用户信息
console.log(userStore.userName);
console.log(userStore.userAvatar);
console.log(userStore.isLoggedIn);
</script> </script>
``` ```
......
<script setup lang="ts"> <script setup lang="ts">
// 根组件入口
</script> </script>
<template> <template>
......
...@@ -2,3 +2,4 @@ ...@@ -2,3 +2,4 @@
* API 统一导出 * API 统一导出
*/ */
export * from './user'; export * from './user';
export * from './route';
/**
* 路由和菜单相关 API
*/
import type { ApiResponse } from '@/types/api';
import type { MenuItem, TopMenuItem } from '@/types/menu';
import type { RouteRecordRaw } from 'vue-router';
const ROUTER_URL = 'https://config-center-backend.glsx.com.cn/glsxAdmin/config?moduleUrl=venus-agentic-router';
// import { get } from '@/utils/request'; // 取消注释以使用真实 API
/**
* 路由配置接口(从 API 返回的数据结构)
*/
export interface RouteConfig {
/** 路由路径 */
path: string;
/** 路由名称 */
name: string;
/** 路由标题 */
title: string;
/** 路由层级 */
level?: number;
/** 是否为微应用 */
isMicroApp?: boolean;
/** 是否需要认证 */
requiresAuth?: boolean;
/** 权限标识 */
permissions?: string[];
/** 角色标识 */
roles?: string[];
}
/**
* 菜单配置接口(从 API 返回的数据结构)
*/
export interface MenuConfig {
/** 顶部菜单列表 */
topMenus: Array<{
id: string;
title: string;
path: string;
icon?: string;
sidebarMenus: Array<{
id: string;
title: string;
path: string;
icon?: string;
level?: number;
parentId?: string;
children?: MenuConfig['topMenus'][0]['sidebarMenus'];
meta?: MenuItem['meta'];
}>;
}>;
/** 路由配置列表 */
routes: RouteConfig[];
}
/**
* 获取路由和菜单配置
* @returns Promise<路由和菜单配置>
*/
export const getRouteConfig = async () => {
// TODO: 替换为实际的 API 端点
// 示例:return get<ApiResponse<MenuConfig>>('/api/routes/menus');
// 临时返回模拟数据,实际使用时需要替换为真实 API
// return Promise.resolve({
// code: 200,
// message: 'success',
// data: {
// topMenus: [],
// routes: [],
// },
// } as ApiResponse<MenuConfig>);
const response = await fetch(ROUTER_URL);
const result = await response.json();
return result;
};
/**
* 将 API 返回的路由配置转换为 Vue Router 路由格式
*/
export function transformRouteConfig(config: RouteConfig): RouteRecordRaw {
// 微应用路由使用 MicroApp 组件
const component = config.isMicroApp
? () => import('@/views/MicroApp.vue')
: // 非微应用路由需要根据实际情况设置组件
// 如果 API 返回了组件路径,可以在这里动态导入
// 示例:() => import(`@/views/${config.component}.vue`);
// 目前暂时使用 MicroApp 作为默认组件,实际使用时需要根据 API 返回的数据设置
() => import('@/views/MicroApp.vue');
return {
path: config.path,
name: config.name,
component,
meta: {
title: config.title,
level: config.level,
isMicroApp: config.isMicroApp,
requiresAuth: config.requiresAuth !== false,
permissions: config.permissions,
roles: config.roles,
},
};
}
/**
* 将 API 返回的菜单配置转换为菜单格式
*/
export function transformMenuConfig(config: MenuConfig): {
topMenus: TopMenuItem[];
routes: RouteRecordRaw[];
} {
const topMenus: TopMenuItem[] = config.topMenus.map((topMenu) => ({
id: topMenu.id,
title: topMenu.title,
path: topMenu.path,
icon: topMenu.icon,
sidebarMenus: transformSidebarMenus(topMenu.sidebarMenus),
}));
const routes: RouteRecordRaw[] = config.routes.map(transformRouteConfig);
return { topMenus, routes };
}
/**
* 递归转换侧边栏菜单
*/
function transformSidebarMenus(
menus: MenuConfig['topMenus'][0]['sidebarMenus'],
): MenuItem[] {
return menus.map((menu) => ({
id: menu.id,
title: menu.title,
path: menu.path,
icon: menu.icon,
level: menu.level,
parentId: menu.parentId,
children: menu.children
? transformSidebarMenus(menu.children)
: undefined,
meta: menu.meta,
}));
}
<script setup lang="ts">
import { useAppStore } from '@/stores';
const appStore = useAppStore();
</script>
<template>
<Transition name="fade">
<div v-if="appStore.loading" class="global-loading">
<div class="loading-content">
<div class="loading-spinner"></div>
<p class="loading-text">正在加载子应用...</p>
</div>
</div>
</Transition>
</template>
<style scoped>
.global-loading {
position: absolute;
top: 0;
left: 0;
z-index: 9999;
display: flex;
align-items: center;
justify-content: center;
width: 100%;
height: 100%;
background: rgb(255 255 255 / 80%);
backdrop-filter: blur(4px);
}
.loading-content {
display: flex;
flex-direction: column;
align-items: center;
gap: 16px;
}
.loading-spinner {
width: 48px;
height: 48px;
border: 4px solid #f3f3f3;
border-top: 4px solid #1890ff;
border-radius: 50%;
animation: spin 1s linear infinite;
}
.loading-text {
margin: 0;
font-size: 14px;
color: #666;
}
@keyframes spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
.fade-enter-active,
.fade-leave-active {
transition: opacity 0.3s ease;
}
.fade-enter-from,
.fade-leave-to {
opacity: 0;
}
</style>
...@@ -7,7 +7,7 @@ import { Request } from 'glsk-toolkit'; ...@@ -7,7 +7,7 @@ import { Request } from 'glsk-toolkit';
// 配置数据 // 配置数据
let baseConfig: any = {}; let baseConfig: any = {};
let routerConfig: any = {};
// GSC API 请求实例(模块级单例,不挂载到 window) // GSC API 请求实例(模块级单例,不挂载到 window)
let gscApiInstance: Request | null = null; let gscApiInstance: Request | null = null;
...@@ -17,6 +17,7 @@ let configReadyResolve: (() => void) | null = null; ...@@ -17,6 +17,7 @@ let configReadyResolve: (() => void) | null = null;
// 配置请求 URL // 配置请求 URL
const CONFIG_URL = 'https://config-center-backend.glsx.com.cn/glsxAdmin/config?moduleUrl=venus-base-system-config'; const CONFIG_URL = 'https://config-center-backend.glsx.com.cn/glsxAdmin/config?moduleUrl=venus-base-system-config';
const ROUTER_URL = 'https://config-center-backend.glsx.com.cn/glsxAdmin/config?moduleUrl=venus-agentic-router';
// 初始化配置就绪 Promise // 初始化配置就绪 Promise
function initConfigReadyPromise() { function initConfigReadyPromise() {
...@@ -61,23 +62,10 @@ export async function fetchConfig(): Promise<any> { ...@@ -61,23 +62,10 @@ export async function fetchConfig(): Promise<any> {
try { try {
const response = await fetch(CONFIG_URL); const response = await fetch(CONFIG_URL);
const result = await response.json(); const result = await response.json();
console.log('[配置中心] 响应结果:', result);
const { code, data } = result; const configData = result;
console.log('[配置中心] 响应结果:', code, result); baseConfig = result;
window.$fetchConfig = result;
// 根据 code 决定使用的配置数据
const configData = code === '200' ? data : result;
if (code === '200') {
console.log('[配置中心] 配置数据:', data);
baseConfig = data;
window.$fetchConfig = data;
} else {
// 如果 code 不是 200,也保存配置
baseConfig = result;
window.$fetchConfig = result;
}
// 统一初始化 GSC API(无论 code 是什么,只要有配置就初始化) // 统一初始化 GSC API(无论 code 是什么,只要有配置就初始化)
const gscConfig = configData?.gsc || configData; const gscConfig = configData?.gsc || configData;
if (gscConfig) { if (gscConfig) {
...@@ -97,10 +85,10 @@ export async function fetchConfig(): Promise<any> { ...@@ -97,10 +85,10 @@ export async function fetchConfig(): Promise<any> {
}, },
}, },
// Sentry 配置 // Sentry 配置
sentry: { // sentry: {
enable: true, // 是否启用Sentry错误上报 // enable: true, // 是否启用Sentry错误上报
dsn: 'https://ace1d827739e4229887b78468bd8a385@sentry.glsx.com.cn/48' // dsn: 'https://ace1d827739e4229887b78468bd8a385@sentry.glsx.com.cn/48'
} // }
}); });
console.log('[配置中心] GSC API 实例创建成功:', gscApiInstance); console.log('[配置中心] GSC API 实例创建成功:', gscApiInstance);
...@@ -132,6 +120,18 @@ export function getConfig(): any { ...@@ -132,6 +120,18 @@ export function getConfig(): any {
return baseConfig; return baseConfig;
} }
export async function fetchRouterConfig(): Promise<any> {
const response = await fetch(ROUTER_URL);
const result = await response.json();
routerConfig = result;
console.log('[配置中心] 路由配置响应结果:', result);
return result;
}
export function getRouterConfig(): any {
return routerConfig;
}
/** /**
* 设置配置数据 * 设置配置数据
* @param config 配置数据 * @param config 配置数据
......
...@@ -3,138 +3,35 @@ import type { MenuItem, TopMenuItem } from '@/types/menu'; ...@@ -3,138 +3,35 @@ import type { MenuItem, TopMenuItem } from '@/types/menu';
/** /**
* 侧边栏菜单配置示例 * 侧边栏菜单配置示例
* 支持一级、二级、三级菜单结构 * 支持一级、二级、三级菜单结构
* 注意:这些是默认菜单配置,实际菜单将从 API 动态获取并存储在 menu store 中
*/ */
// 首页侧边栏菜单 // 首页侧边栏菜单
export const homeMenus: MenuItem[] = [ export const homeMenus: MenuItem[] = [
{
id: 'dashboard',
title: '工作台',
path: '/home/dashboard',
icon: '📊',
level: 1,
}
]; ];
// Vue 微应用侧边栏菜单(多级嵌套示例) // Vue 微应用侧边栏菜单(多级嵌套示例)
// 支持一级、二级、三级菜单嵌套结构 // 支持一级、二级、三级菜单嵌套结构
// 注意:此配置仅作为后备方案,实际菜单将从 API 动态获取
export const vueAppMenus: MenuItem[] = [ export const vueAppMenus: MenuItem[] = [
{
id: 'contacts',
title: '智能助理',
path: '/subapp-vue/',
icon: '🤖',
level: 1,
children: [
{
id: 'contacts-config',
title: '首页',
path: '/subapp-vue/',
icon: '⚙️',
level: 2,
parentId: 'contacts',
children: [],
},
{
id: 'contacts-config',
title: '岗位助理配置',
path: '/subapp-vue/assistant',
icon: '⚙️',
level: 2,
parentId: 'contacts',
children: [],
},
{
id: 'contacts-knowledge',
title: '知识管理',
path: '/subapp-vue/managekonw',
icon: '📚',
level: 2,
parentId: 'contacts',
children: [],
},
{
id: 'contacts-agent',
title: '智能体管理',
path: '/subapp-vue/communications',
icon: '🎯',
level: 2,
parentId: 'contacts',
children: [
{
id: 'contacts-agent-list',
title: '智能体列表',
path: '/subapp-vue/communications/list',
icon: '📋',
level: 3,
parentId: 'contacts-agent',
},
{
id: 'contacts-agent-create',
title: '创建智能体',
path: '/subapp-vue/communications/create',
icon: '➕',
level: 3,
parentId: 'contacts-agent',
},
{
id: 'contacts-agent-training',
title: '训练管理',
path: '/subapp-vue/communications/training',
icon: '🎓',
level: 3,
parentId: 'contacts-agent',
children: [
{
id: 'contacts-agent-training-data',
title: '训练数据',
path: '/subapp-vue/communications/training/data',
icon: '💾',
level: 4,
parentId: 'contacts-agent-training',
},
{
id: 'contacts-agent-training-model',
title: '模型训练',
path: '/subapp-vue/communications/training/model',
icon: '🧠',
level: 4,
parentId: 'contacts-agent-training',
},
],
},
],
},
],
},
]; ];
/** /**
* 顶部导航菜单配置 * 默认顶部导航菜单配置
* 每个顶部菜单可以关联不同的侧边栏菜单 * 每个顶部菜单可以关联不同的侧边栏菜单
* 注意:实际菜单将从 API 动态获取,此配置仅作为后备方案
*/ */
export const topMenus: TopMenuItem[] = [ export const defaultTopMenus: TopMenuItem[] = [
{
id: 'home',
title: '首页',
path: '/home/dashboard',
icon: '',
sidebarMenus: homeMenus,
},
{
id: 'vue-app',
title: '微应用',
path: '/subapp-vue',
icon: '',
sidebarMenus: vueAppMenus,
},
]; ];
/** /**
* 根据路径获取对应的侧边栏菜单 * 根据路径获取对应的侧边栏菜单
* 注意:此函数已废弃,请使用 menu store 中的 getSidebarMenusByPath 方法
* @deprecated 请使用 useMenuStore().getSidebarMenusByPath()
*/ */
export function getSidebarMenusByPath(path: string): MenuItem[] { export function getSidebarMenusByPath(path: string): MenuItem[] {
const topMenu = topMenus.find((menu) => path.startsWith(menu.path)); const topMenu = defaultTopMenus.find((menu) => path.startsWith(menu.path));
return topMenu?.sidebarMenus || []; return topMenu?.sidebarMenus || [];
} }
......
...@@ -7,12 +7,14 @@ import NotificationCenter from './components/NotificationCenter.vue'; ...@@ -7,12 +7,14 @@ import NotificationCenter from './components/NotificationCenter.vue';
import SidebarMenuItem from './components/SidebarMenuItem.vue'; import SidebarMenuItem from './components/SidebarMenuItem.vue';
import UserInfo from './components/UserInfo.vue'; import UserInfo from './components/UserInfo.vue';
import { Download } from '@element-plus/icons-vue'; import { Download } from '@element-plus/icons-vue';
import { getMenuParentPaths, topMenus } from '@/config/menus'; import { getMenuParentPaths, defaultTopMenus } from '@/config/menus';
import { microApps } from '@/qiankun/apps'; import { microApps } from '@/qiankun/apps';
import { communicationManager } from '@/qiankun/communication'; import { communicationManager } from '@/qiankun/communication';
import { useMenuStore } from '@/stores';
const router = useRouter(); const router = useRouter();
const route = useRoute(); const route = useRoute();
const menuStore = useMenuStore();
// 应用名称(从环境变量读取) // 应用名称(从环境变量读取)
const appName ='汽车销售智能体'; const appName ='汽车销售智能体';
...@@ -23,10 +25,21 @@ const expandedKeys = ref<Set<string>>(new Set()); ...@@ -23,10 +25,21 @@ const expandedKeys = ref<Set<string>>(new Set());
// 当前激活的顶级菜单 ID // 当前激活的顶级菜单 ID
const activeTopMenuId = ref<string>(''); const activeTopMenuId = ref<string>('');
// 获取顶部菜单(优先使用动态菜单,如果没有则使用默认菜单)
const topMenus = computed(() => {
return menuStore.isMenusLoaded && menuStore.topMenus.length > 0
? menuStore.topMenus
: defaultTopMenus;
});
// 获取所有菜单(用于面包屑和路由查找) // 获取所有菜单(用于面包屑和路由查找)
const allMenus = computed(() => { const allMenus = computed(() => {
// 优先使用 store 中的菜单,如果没有则使用默认菜单
if (menuStore.isMenusLoaded && menuStore.topMenus.length > 0) {
return menuStore.getAllMenus();
}
const menus: MenuItem[] = []; const menus: MenuItem[] = [];
topMenus.forEach((topMenu) => { defaultTopMenus.forEach((topMenu) => {
if (topMenu.sidebarMenus) { if (topMenu.sidebarMenus) {
menus.push(...topMenu.sidebarMenus); menus.push(...topMenu.sidebarMenus);
} }
...@@ -36,7 +49,7 @@ const allMenus = computed(() => { ...@@ -36,7 +49,7 @@ const allMenus = computed(() => {
// 根据当前路由判断激活的顶级菜单 // 根据当前路由判断激活的顶级菜单
const getActiveTopMenuId = (path: string): string => { const getActiveTopMenuId = (path: string): string => {
for (const topMenu of topMenus) { for (const topMenu of topMenus.value) {
if (path.startsWith(topMenu.path)) { if (path.startsWith(topMenu.path)) {
return topMenu.id; return topMenu.id;
} }
...@@ -52,7 +65,8 @@ const breadcrumbs = computed<BreadcrumbItem[]>(() => { ...@@ -52,7 +65,8 @@ const breadcrumbs = computed<BreadcrumbItem[]>(() => {
// 如果不在首页,添加当前路由的面包屑 // 如果不在首页,添加当前路由的面包屑
if (route.path !== '/home' && route.path !== '/') { if (route.path !== '/home' && route.path !== '/') {
const paths = getMenuParentPaths(allMenus.value, route.path); const paths = getMenuParentPaths(allMenus.value, route.path);
console.log("路由调用", paths, menuStore.isMenusLoaded ? '动态菜单' : '默认菜单');
// 根据路径找到对应的菜单项 // 根据路径找到对应的菜单项
paths.forEach((path) => { paths.forEach((path) => {
const menu = findMenuByPath(allMenus.value, path); const menu = findMenuByPath(allMenus.value, path);
......
...@@ -3,10 +3,11 @@ import { createApp } from 'vue'; ...@@ -3,10 +3,11 @@ import { createApp } from 'vue';
import { createPinia } from 'pinia'; import { createPinia } from 'pinia';
import App from './App.vue'; import App from './App.vue';
import { getRouteConfig, transformMenuConfig } from './api/route';
import { fetchConfig, getConfig } from './config/center'; import { fetchConfig, getConfig } from './config/center';
import { setupQiankun } from './qiankun'; import { setupQiankun } from './qiankun';
import router from './router'; import router, { addLayoutRoutes } from './router';
import { useAppStore, useUserStore } from './stores'; import { useAppStore, useMenuStore, useUserStore } from './stores';
import { getToken } from './utils/auth'; import { getToken } from './utils/auth';
import './style.css'; import './style.css';
...@@ -22,6 +23,36 @@ app.use(pinia); ...@@ -22,6 +23,36 @@ app.use(pinia);
// 注册路由 // 注册路由
app.use(router); app.use(router);
/**
* 加载动态路由和菜单配置
*/
async function loadDynamicRoutes() {
try {
const menuStore = useMenuStore();
// 如果已经加载过,则不再重复加载
if (menuStore.isMenusLoaded) return;
// 调用 API 获取路由和菜单配置
const response = await getRouteConfig();
if (response.code === 200 && response.data) {
const { topMenus, routes } = transformMenuConfig(response.data);
// 更新菜单 store
menuStore.setTopMenus(topMenus);
// 动态添加路由到 Layout 的 children 中
if (routes.length > 0) {
addLayoutRoutes(routes);
menuStore.addDynamicRoutes(routes);
}
}
} catch (error) {
console.error('[基座] 加载动态路由和菜单配置失败将使用默认菜单配置:', error);
}
}
// 应用初始化 // 应用初始化
async function initApp() { async function initApp() {
try { try {
...@@ -38,13 +69,12 @@ async function initApp() { ...@@ -38,13 +69,12 @@ async function initApp() {
// 尝试获取用户信息(如果失败,路由守卫会处理) // 尝试获取用户信息(如果失败,路由守卫会处理)
try { try {
await userStore.getUserInfo(); await userStore.getUserInfo();
console.log('[基座] 用户信息恢复成功,已同步到 qiankun 全局状态'); // 用户信息获取成功后,加载动态路由和菜单
await loadDynamicRoutes();
} catch { } catch {
console.warn('[基座] 用户信息恢复失败,将在路由守卫中重新登录'); console.warn('[基座] 用户信息恢复失败,将在路由守卫中重新登录');
} }
} }
console.log('[基座] 应用初始化完成');
} catch (error) { } catch (error) {
console.error('[基座] 应用初始化失败:', error); console.error('[基座] 应用初始化失败:', error);
} }
...@@ -57,7 +87,6 @@ function setupStoreSync() { ...@@ -57,7 +87,6 @@ function setupStoreSync() {
// 监听用户信息变化 // 监听用户信息变化
userStore.$subscribe(() => { userStore.$subscribe(() => {
console.log('[基座] 用户 Store 变化,同步到 qiankun 全局状态');
// 每次 Store 变化时,同步用户信息 // 每次 Store 变化时,同步用户信息
userStore.syncUserToQiankun(); userStore.syncUserToQiankun();
}); });
...@@ -69,7 +98,6 @@ function setupStoreSync() { ...@@ -69,7 +98,6 @@ function setupStoreSync() {
mode: state.theme, mode: state.theme,
primaryColor: state.theme === 'dark' ? '#177ddc' : '#1890ff', primaryColor: state.theme === 'dark' ? '#177ddc' : '#1890ff',
}); });
console.log('[基座] 主题已同步到 qiankun 全局状态');
}); });
}); });
} }
......
...@@ -10,8 +10,14 @@ export const microAppLifecycles: FrameworkLifeCycles<any> = { ...@@ -10,8 +10,14 @@ export const microAppLifecycles: FrameworkLifeCycles<any> = {
beforeLoad: async (app) => { beforeLoad: async (app) => {
console.log('[qiankun] before load', app.name); console.log('[qiankun] before load', app.name);
// 可以在这里做一些加载前的准备工作 // 显示加载状态
// 例如:显示加载动画、设置全局状态等 try {
const { useAppStore } = await import('@/stores');
const appStore = useAppStore();
appStore.setLoading(true);
} catch (error) {
console.warn('[qiankun] 设置加载状态失败:', error);
}
}, },
/** /**
...@@ -44,8 +50,14 @@ export const microAppLifecycles: FrameworkLifeCycles<any> = { ...@@ -44,8 +50,14 @@ export const microAppLifecycles: FrameworkLifeCycles<any> = {
afterMount: async (app) => { afterMount: async (app) => {
console.log('[qiankun] after mount', app.name); console.log('[qiankun] after mount', app.name);
// 可以在这里做一些挂载后的处理 // 隐藏加载状态
// 例如:隐藏加载动画、记录日志、埋点统计等 try {
const { useAppStore } = await import('@/stores');
const appStore = useAppStore();
appStore.setLoading(false);
} catch (error) {
console.warn('[qiankun] 清除加载状态失败:', error);
}
}, },
/** /**
...@@ -64,7 +76,13 @@ export const microAppLifecycles: FrameworkLifeCycles<any> = { ...@@ -64,7 +76,13 @@ export const microAppLifecycles: FrameworkLifeCycles<any> = {
afterUnmount: async (app) => { afterUnmount: async (app) => {
console.log('[qiankun] after unmount', app.name); console.log('[qiankun] after unmount', app.name);
// 可以在这里做一些卸载后的清理工作 // 确保清除加载状态
// 例如:清除缓存、重置状态、移除事件监听等 try {
const { useAppStore } = await import('@/stores');
const appStore = useAppStore();
appStore.setLoading(false);
} catch (error) {
console.warn('[qiankun] 清除加载状态失败:', error);
}
}, },
}; };
import type { RouteRecordRaw } from 'vue-router'; import type { RouteRecordRaw } from 'vue-router';
import { createRouter, createWebHistory } from 'vue-router'; import { createRouter, createWebHistory } from 'vue-router';
import { getRouteConfig, transformMenuConfig } from '@/api/route';
import { useUserStore } from '@/stores'; import { getMicroAppByPath } from '@/qiankun/apps';
import { useAppStore, useMenuStore, useUserStore } from '@/stores';
import { getToken } from '@/utils/auth'; import { getToken } from '@/utils/auth';
/** /**
* 路由配置 * 路由配置
* 支持多级路由嵌套,配合菜单系统实现多级导航 * 支持多级路由嵌套,配合菜单系统实现多级导航
* 注意:Vue 微应用模块路由将通过 API 动态添加
*/ */
const routes: RouteRecordRaw[] = [ const routes: RouteRecordRaw[] = [
// ==================== 登录页面 ====================
{ {
path: '/login', path: '/login',
name: 'Login', name: 'Login',
...@@ -52,35 +52,11 @@ const routes: RouteRecordRaw[] = [ ...@@ -52,35 +52,11 @@ const routes: RouteRecordRaw[] = [
level: 2, level: 2,
requiresAuth: true, requiresAuth: true,
}, },
}, }
{
path: 'analytics',
name: 'Analytics',
component: () => import('@/views/Home.vue'),
meta: {
title: '数据概览',
level: 2,
requiresAuth: true,
},
},
], ],
}, },
// ==================== Vue 微应用模块 ====================
{
path: '/subapp-vue/:pathMatch(.*)*',
name: 'SubAppVue',
component: () => import('@/views/MicroApp.vue'),
meta: {
title: 'Vue 微应用',
level: 1,
isMicroApp: true,
requiresAuth: true,
},
},
], ],
}, },
// ==================== 404 页面 ==================== // ==================== 404 页面 ====================
{ {
path: '/:pathMatch(.*)*', path: '/:pathMatch(.*)*',
...@@ -98,9 +74,132 @@ const router = createRouter({ ...@@ -98,9 +74,132 @@ const router = createRouter({
routes, routes,
}); });
/**
* 动态添加路由
* @param routes 要添加的路由配置数组
* @param parentName 父路由名称,如果提供,则添加到该父路由的 children 中
*/
export function addRoutes(routes: RouteRecordRaw[], parentName?: string) {
if (parentName) {
// 添加到指定父路由的 children 中
const parentRoute = router.getRoutes().find((route) => route.name === parentName);
if (parentRoute) {
routes.forEach((route) => {
router.addRoute(parentName, route);
});
} else {
console.warn(`[路由] 未找到父路由 "${parentName}"`);
}
} else {
// 直接添加到根路由
routes.forEach((route) => {
router.addRoute(route);
});
}
}
/**
* 动态添加子路由到 Layout
* @param routes 要添加的路由配置数组
*/
export function addLayoutRoutes(routes: RouteRecordRaw[]) {
addRoutes(routes, 'Layout');
}
// 白名单:不需要登录的路由 // 白名单:不需要登录的路由
const whiteList = new Set(['/forgot-password', '/login', '/register']); const whiteList = new Set(['/forgot-password', '/login', '/register']);
// 标记是否正在加载动态路由
let isLoadingRoutes = false;
/**
* 加载动态路由和菜单配置
*/
async function loadDynamicRoutes() {
// 防止重复加载
if (isLoadingRoutes) {
return;
}
const menuStore = useMenuStore();
// 如果已经加载过,则不再重复加载
if (menuStore.isMenusLoaded) {
return;
}
try {
isLoadingRoutes = true;
// 调用 API 获取路由和菜单配置
const response = await getRouteConfig();
if (response.code === 200 && response.data) {
const { topMenus, routes } = transformMenuConfig(response.data);
// 更新菜单 store
menuStore.setTopMenus(topMenus);
// 动态添加路由到 Layout 的 children 中
if (routes.length > 0) {
addLayoutRoutes(routes);
menuStore.addDynamicRoutes(routes);
}
}
} catch (error) {
console.error('[路由守卫] 加载动态路由和菜单配置失败将使用默认菜单配置:', error);
} finally {
isLoadingRoutes = false;
}
}
/**
* 检查路径是否可能是子应用路由
* @param path 路由路径
*/
function isPossibleMicroAppPath(path: string): boolean {
// 检查路径是否以已知的微应用 activeRule 开头
const microApp = getMicroAppByPath(path);
return !!microApp;
}
/**
* 等待动态路由加载完成并重新匹配路由
* @param targetPath 目标路径
*/
async function waitForRoutesAndRematch(targetPath: string): Promise<boolean> {
const appStore = useAppStore();
const menuStore = useMenuStore();
// 如果已经加载过,检查路由是否匹配
if (menuStore.isMenusLoaded) {
const matchedRoutes = router.resolve(targetPath);
return matchedRoutes.name !== 'NotFound';
}
// 显示 loading
appStore.setLoading(true);
try {
// 等待动态路由加载完成(loadDynamicRoutes 内部有防重复加载逻辑)
await loadDynamicRoutes();
// 等待一小段时间,确保路由已经添加到 router 中
await new Promise(resolve => setTimeout(resolve, 100));
// 检查路由是否已存在
const matchedRoutes = router.resolve(targetPath);
const isMatched = matchedRoutes.name !== 'NotFound';
return isMatched;
} catch (error) {
console.error('[路由守卫] 等待动态路由加载失败:', error);
return false;
} finally {
// 隐藏 loading
appStore.setLoading(false);
}
}
/** /**
* 全局前置守卫 * 全局前置守卫
*/ */
...@@ -117,6 +216,29 @@ router.beforeEach(async (to, _from, next) => { ...@@ -117,6 +216,29 @@ router.beforeEach(async (to, _from, next) => {
// 判断是否需要认证 // 判断是否需要认证
const requiresAuth = to.meta.requiresAuth !== false; const requiresAuth = to.meta.requiresAuth !== false;
// 如果匹配到404路由,检查是否是子应用路由
if (to.name === 'NotFound' && token) {
// 检查当前路径是否可能是子应用路由
if (isPossibleMicroAppPath(to.path)) {
console.log('[路由守卫] 检测到可能的子应用路由,等待动态路由加载:', to.path);
// 等待动态路由加载完成
const isMatched = await waitForRoutesAndRematch(to.path);
if (isMatched) {
// 路由已匹配,重新导航到目标路径
console.log('[路由守卫] 动态路由加载完成,重新导航到:', to.path);
next({ path: to.path, replace: true });
return;
} else {
// 确实不存在,显示404页面
console.log('[路由守卫] 动态路由加载完成,但路由不存在,显示404页面');
next();
return;
}
}
}
if (token) { if (token) {
// 已登录 // 已登录
if (to.path === '/login') { if (to.path === '/login') {
...@@ -125,6 +247,9 @@ router.beforeEach(async (to, _from, next) => { ...@@ -125,6 +247,9 @@ router.beforeEach(async (to, _from, next) => {
} else { } else {
// 检查是否已获取用户信息 // 检查是否已获取用户信息
if (userStore.userInfo) { if (userStore.userInfo) {
// 确保动态路由已加载
await loadDynamicRoutes();
// 检查权限 // 检查权限
if (to.meta.permissions || to.meta.roles) { if (to.meta.permissions || to.meta.roles) {
const hasPermission = checkPermission(to, userStore); const hasPermission = checkPermission(to, userStore);
...@@ -136,7 +261,6 @@ router.beforeEach(async (to, _from, next) => { ...@@ -136,7 +261,6 @@ router.beforeEach(async (to, _from, next) => {
next(); next();
} else { } else {
// 无权限,跳转到 403 或首页 // 无权限,跳转到 403 或首页
console.warn('无权限访问:', to.path);
next({ path: '/home' }); next({ path: '/home' });
} }
} else { } else {
...@@ -151,6 +275,9 @@ router.beforeEach(async (to, _from, next) => { ...@@ -151,6 +275,9 @@ router.beforeEach(async (to, _from, next) => {
// 获取用户信息(会自动同步到 qiankun 全局状态) // 获取用户信息(会自动同步到 qiankun 全局状态)
await userStore.getUserInfo(); await userStore.getUserInfo();
// 用户信息获取成功后,加载动态路由和菜单
await loadDynamicRoutes();
// 如果是微应用路由,确保数据已同步 // 如果是微应用路由,确保数据已同步
if (to.meta.isMicroApp) { if (to.meta.isMicroApp) {
await syncDataToQiankun(userStore); await syncDataToQiankun(userStore);
...@@ -159,7 +286,6 @@ router.beforeEach(async (to, _from, next) => { ...@@ -159,7 +286,6 @@ router.beforeEach(async (to, _from, next) => {
next(); next();
} catch (error) { } catch (error) {
// 获取用户信息失败,清除 token 并跳转到登录页 // 获取用户信息失败,清除 token 并跳转到登录页
console.error('获取用户信息失败:', error);
await userStore.logout(); await userStore.logout();
next({ next({
path: '/login', path: '/login',
...@@ -212,11 +338,9 @@ async function syncDataToQiankun(userStore: any): Promise<void> { ...@@ -212,11 +338,9 @@ async function syncDataToQiankun(userStore: any): Promise<void> {
// 获取当前全局状态,确认数据已同步 // 获取当前全局状态,确认数据已同步
const globalState = communicationManager.getGlobalState(); const globalState = communicationManager.getGlobalState();
console.log('[路由守卫] 当前全局状态:', globalState);
// 如果用户信息还未同步,强制同步一次 // 如果用户信息还未同步,强制同步一次
if (!globalState.user && userStore.userInfo) { if (!globalState.user && userStore.userInfo) {
console.log('[路由守卫] 检测到用户信息未同步,强制同步');
communicationManager.updateUser({ communicationManager.updateUser({
id: userStore.userInfo.id, id: userStore.userInfo.id,
name: userStore.userInfo.name, name: userStore.userInfo.name,
......
...@@ -3,5 +3,6 @@ ...@@ -3,5 +3,6 @@
*/ */
export { useAppStore } from './app'; export { useAppStore } from './app';
export { useMenuStore } from './menu';
export { usePermissionStore } from './permission'; export { usePermissionStore } from './permission';
export { useUserStore } from './user'; export { useUserStore } from './user';
import type { MenuItem, TopMenuItem } from '@/types/menu';
import type { RouteRecordRaw } from 'vue-router';
import { ref } from 'vue';
import { defineStore } from 'pinia';
/**
* 菜单状态管理
* 用于管理动态菜单和路由配置
*/
export const useMenuStore = defineStore('menu', () => {
// 动态菜单数据
const topMenus = ref<TopMenuItem[]>([]);
const dynamicRoutes = ref<RouteRecordRaw[]>([]);
// 是否已加载菜单
const isMenusLoaded = ref(false);
/**
* 设置顶部菜单
*/
const setTopMenus = (menus: TopMenuItem[]) => {
topMenus.value = menus;
isMenusLoaded.value = true;
};
/**
* 添加动态路由
*/
const addDynamicRoutes = (routes: RouteRecordRaw[]) => {
dynamicRoutes.value = routes;
};
/**
* 根据路径获取对应的侧边栏菜单
*/
const getSidebarMenusByPath = (path: string): MenuItem[] => {
const topMenu = topMenus.value.find((menu) => path.startsWith(menu.path));
return topMenu?.sidebarMenus || [];
};
/**
* 获取所有菜单(扁平化)
*/
const getAllMenus = (): MenuItem[] => {
const menus: MenuItem[] = [];
topMenus.value.forEach((topMenu) => {
if (topMenu.sidebarMenus) {
menus.push(...topMenu.sidebarMenus);
}
});
return menus;
};
/**
* 重置状态
*/
const reset = () => {
topMenus.value = [];
dynamicRoutes.value = [];
isMenusLoaded.value = false;
};
return {
topMenus,
dynamicRoutes,
isMenusLoaded,
setTopMenus,
addDynamicRoutes,
getSidebarMenusByPath,
getAllMenus,
reset,
};
});
...@@ -31,13 +31,10 @@ let unsubscribe: (() => void) | null = null; ...@@ -31,13 +31,10 @@ let unsubscribe: (() => void) | null = null;
// GLButton 组件演示相关状态 // GLButton 组件演示相关状态
const buttonLoading = ref(false); const buttonLoading = ref(false);
const clickCount = ref(0); const clickCount = ref(0);
// 初始化:获取全局状态并监听变化
onMounted(async () => { onMounted(async () => {
// 等待配置加载完成后再发起请求
try { try {
await waitForConfigReady(); await waitForConfigReady();
console.log('[Home] 配置已就绪,开始请求数据看板...'); console.log('[Home] 配置已就绪,开始请求数据看板...');
const res = await getdataBoard({merchantNos: '', dateType: '1', startDate: '', endDate: ''}); const res = await getdataBoard({merchantNos: '', dateType: '1', startDate: '', endDate: ''});
console.log('[Home] 数据看板请求成功:', res); console.log('[Home] 数据看板请求成功:', res);
} catch (err: any) { } catch (err: any) {
......
<script setup lang="ts"> <script setup lang="ts">
import GlobalLoading from '@/components/GlobalLoading.vue';
import { onMounted, onUnmounted } from 'vue'; import { onMounted, onUnmounted } from 'vue';
import { useRoute } from 'vue-router'; import { useRoute } from 'vue-router';
...@@ -14,11 +15,22 @@ onUnmounted(() => { ...@@ -14,11 +15,22 @@ onUnmounted(() => {
</script> </script>
<template> <template>
<!-- qiankun 微应用容器 - 作为唯一的微应用挂载点 --> <div class="micro-app-wrapper">
<div id="subapp-container" class="micro-app-container"></div> <!-- qiankun 微应用容器 - 作为唯一的微应用挂载点 -->
<div id="subapp-container" class="micro-app-container"></div>
<!-- 子应用加载中的 loading -->
<GlobalLoading />
</div>
</template> </template>
<style scoped> <style scoped>
.micro-app-wrapper {
position: relative;
width: 100%;
height: 100%;
min-height: 500px;
}
.micro-app-container { .micro-app-container {
width: 100%; width: 100%;
height: 100%; height: 100%;
......
...@@ -25,7 +25,7 @@ const goHome = () => { ...@@ -25,7 +25,7 @@ const goHome = () => {
align-items: center; align-items: center;
justify-content: center; justify-content: center;
min-height: 100vh; min-height: 100vh;
background: linear-gradient(135deg, #eff2ff 0%, #f6edff 100%); background: linear-gradient(135deg, #ffffff 0%, #ffffff 100%);
} }
.not-found-content { .not-found-content {
...@@ -57,7 +57,7 @@ const goHome = () => { ...@@ -57,7 +57,7 @@ const goHome = () => {
padding: 12px 32px; padding: 12px 32px;
font-size: 16px; font-size: 16px;
font-weight: 500; font-weight: 500;
color: #667eea; color: #000000;
cursor: pointer; cursor: pointer;
background: #fff; background: #fff;
border: none; border: none;
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!