web iframe结构实现

This commit is contained in:
2025-12-13 14:13:31 +08:00
parent e002f0d989
commit 1776aa2d1e
53 changed files with 3280 additions and 275 deletions

View File

@@ -51,6 +51,13 @@ window.APP_RUNTIME_CONFIG = {
publicImgPath: '/img',
publicWebPath: '/',
// 单点登录配置
sso: {
platformUrl: '/', // platform 平台地址
workcaseUrl: '/workcase', // workcase 服务地址
biddingUrl: '/bidding' // bidding 服务地址
},
// 功能开关
features: {
enableDebug: false,

View File

@@ -0,0 +1,293 @@
<template>
<div class="sidebar-layout">
<!-- 侧边栏 -->
<aside class="sidebar" :class="{ collapsed: collapsed }">
<div class="sidebar-header">
<div class="logo">
<img src="/logo.jpg" alt="Logo" class="logo-img" />
<span v-if="!collapsed" class="logo-text">城市生命线</span>
</div>
<div class="collapse-btn" @click="toggleSidebar">
<el-icon>
<DArrowLeft v-if="!collapsed" />
<DArrowRight v-else />
</el-icon>
</div>
</div>
<nav class="nav-menu">
<div class="nav-section">
<div
v-for="item in menuItems"
:key="item.key"
class="nav-item"
:class="{ active: activeMenu === item.key }"
@click="handleMenuClick(item)"
>
<el-icon><component :is="item.icon" /></el-icon>
<span v-if="!collapsed">{{ item.label }}</span>
</div>
</div>
</nav>
<!-- 用户信息 -->
<el-dropdown class="user-section" trigger="click" @command="handleUserCommand">
<div class="user-info-wrapper">
<div class="user-avatar">
<el-avatar :size="36" src="/avatar.svg" @error="handleAvatarError" />
</div>
<span v-if="!collapsed" class="user-name">{{ userName }}</span>
</div>
<template #dropdown>
<el-dropdown-menu>
<el-dropdown-item command="profile">
<el-icon><User /></el-icon>
个人中心
</el-dropdown-item>
<el-dropdown-item command="settings" divided>
<el-icon><Setting /></el-icon>
系统设置
</el-dropdown-item>
<el-dropdown-item command="logout" divided>
<el-icon><SwitchButton /></el-icon>
退出登录
</el-dropdown-item>
</el-dropdown-menu>
</template>
</el-dropdown>
</aside>
<!-- 主内容区 -->
<main class="main-content">
<!-- iframe 模式 -->
<div v-if="currentIframeUrl" class="iframe-container">
<div class="iframe-header">
<span class="iframe-title">{{ currentMenuItem?.label }}</span>
<el-button
text
@click="handleRefreshIframe"
:icon="Refresh"
>
刷新
</el-button>
</div>
<iframe
ref="iframeRef"
:src="currentIframeUrl"
class="content-iframe"
frameborder="0"
@load="handleIframeLoad"
/>
<div v-if="iframeLoading" class="iframe-loading">
<el-icon class="is-loading"><Loading /></el-icon>
<span>加载中...</span>
</div>
</div>
<!-- 路由模式 -->
<router-view v-else />
</main>
</div>
</template>
<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import {
ChatDotRound,
Grid,
Connection,
Document,
Service,
DArrowLeft,
DArrowRight,
User,
Setting,
SwitchButton,
Refresh,
Loading
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
interface MenuItem {
key: string
label: string
icon: string
url?: string
type: 'route' | 'iframe'
}
const router = useRouter()
const route = useRoute()
// 状态管理
const collapsed = ref(false)
const activeMenu = ref('home')
const iframeLoading = ref(false)
const iframeRef = ref<HTMLIFrameElement>()
// 从 LocalStorage 获取用户名
function getUserName(): string {
try {
const loginDomainStr = localStorage.getItem('loginDomain')
if (loginDomainStr) {
const loginDomain = JSON.parse(loginDomainStr)
return loginDomain.user?.username || loginDomain.userInfo?.username || '管理员'
}
} catch (error) {
console.error('❌ 获取用户名失败:', error)
}
return '管理员'
}
const userName = ref(getUserName())
/**
* 从 LocalStorage 加载菜单
*/
function loadMenuFromStorage(): MenuItem[] {
try {
const loginDomainStr = localStorage.getItem('loginDomain')
if (!loginDomainStr) {
console.warn('⚠️ 未找到 loginDomain')
return []
}
const loginDomain = JSON.parse(loginDomainStr)
const userViews = loginDomain.userViews || []
console.log('📋 加载用户视图:', userViews)
// 过滤出 SidebarLayout 的顶级菜单(没有 parentId且属于 bidding 服务且不是admin路由
const sidebarViews = userViews.filter((view: any) =>
view.layout === 'SidebarLayout' &&
!view.parentId &&
view.type === 1 && // type 1 是侧边栏菜单
view.service === 'bidding' && // 只显示 bidding 服务的视图
!view.url?.startsWith('/admin') // 排除 admin 路由(由 AdminSidebar 管理)
)
console.log('🔍 过滤后的 bidding 视图:', sidebarViews)
// 按 orderNum 排序
sidebarViews.sort((a: any, b: any) => (a.orderNum || 0) - (b.orderNum || 0))
// 转换为 MenuItem 格式
const menuItems: MenuItem[] = sidebarViews.map((view: any) => {
// 根据 viewType 或 iframeUrl 判断是 route 还是 iframe
const isIframe = view.viewType === 'iframe' || !!view.iframeUrl
// 确定菜单的路由路径
let menuUrl = view.url
if (isIframe && view.url && (view.url.startsWith('http://') || view.url.startsWith('https://'))) {
// iframe 类型且 url 是外部链接,使用 viewId 作为路由路径
menuUrl = `/${view.viewId}`
}
return {
key: view.viewId || view.name,
label: view.name,
icon: view.icon || 'Grid',
url: menuUrl,
type: isIframe ? 'iframe' : 'route'
}
})
console.log('✅ 侧边栏菜单:', menuItems)
return menuItems
} catch (error) {
console.error('❌ 加载菜单失败:', error)
return []
}
}
// 菜单配置(从 LocalStorage 加载)
const menuItems = ref<MenuItem[]>(loadMenuFromStorage())
// 当前菜单项
const currentMenuItem = computed(() => {
return menuItems.value.find(item => item.key === activeMenu.value)
})
// 当前 iframe URL从路由 meta 读取)
const currentIframeUrl = computed(() => {
const meta = route.meta as any
return meta?.iframeUrl || null
})
// 切换侧边栏
const toggleSidebar = () => {
collapsed.value = !collapsed.value
}
// 处理菜单点击
const handleMenuClick = (item: MenuItem) => {
activeMenu.value = item.key
// 所有菜单都通过路由跳转
if (item.url) {
router.push(item.url)
if (item.type === 'iframe') {
iframeLoading.value = true
}
}
}
// iframe 加载完成
const handleIframeLoad = () => {
iframeLoading.value = false
}
// 刷新 iframe
const handleRefreshIframe = () => {
if (iframeRef.value) {
iframeLoading.value = true
iframeRef.value.src = iframeRef.value.src
}
}
// 用户头像加载错误
const handleAvatarError = () => {
return true
}
// 用户操作
const handleUserCommand = (command: string) => {
switch (command) {
case 'profile':
router.push('/profile')
break
case 'settings':
router.push('/settings')
break
case 'logout':
localStorage.clear()
ElMessage.success('退出成功')
router.push('/login')
break
}
}
// 监听路由变化,同步激活菜单
watch(
() => route.path,
(newPath) => {
// 查找匹配的菜单项route 或 iframe 类型)
const menuItem = menuItems.value.find((item: MenuItem) => item.url === newPath)
if (menuItem) {
activeMenu.value = menuItem.key
} else {
// 如果路径不匹配,尝试通过 route.name 匹配 viewId
const menuByName = menuItems.value.find((item: MenuItem) => item.key === route.name)
if (menuByName) {
activeMenu.value = menuByName.key
}
}
},
{ immediate: true }
)
</script>
<style lang="scss" scoped>
@import url("./SidebarLayout.scss");
</style>

View File

@@ -0,0 +1 @@
export { default as SidebarLayout } from './SidebarLayout.vue'

View File

@@ -0,0 +1,3 @@
export { default as SidebarLayout } from './SidebarLayout/SidebarLayout.vue'
// BlankLayout从shared导入
export { BlankLayout } from 'shared/layouts'

View File

@@ -0,0 +1,155 @@
/**
* 动态路由生成模块Bidding 特定)
*
* 职责:
* 1. 提供 Bidding 特定的布局和组件配置
* 2. 调用 shared 中的通用路由生成方法
* 3. 将生成的路由添加到 Bidding 的 router 实例
*/
/// <reference types="vite/client" />
import {
generateSimpleRoutes,
loadViewsFromStorage,
type RouteGeneratorConfig,
type GenerateSimpleRoutesOptions
} from 'shared/utils/route'
import type { TbSysViewDTO } from 'shared/types'
import type { RouteRecordRaw } from 'vue-router'
import router from './index'
import { SidebarLayout, BlankLayout } from '@/layouts'
// Bidding 布局组件映射
const biddingLayoutMap: Record<string, () => Promise<any>> = {
'SidebarLayout': () => Promise.resolve({ default: SidebarLayout }),
'BlankLayout': () => Promise.resolve({ default: BlankLayout }),
'NavigationLayout': () => Promise.resolve({ default: SidebarLayout }),
'BasicLayout': () => Promise.resolve({ default: SidebarLayout })
}
// 视图组件加载器
const VIEW_MODULES = import.meta.glob<{ default: any }>('../views/**/*.vue')
/**
* 视图组件加载函数
* @param componentPath 组件路径(如 "bidding/Home" 或 "bidding/List"
*/
function viewLoader(componentPath: string): (() => Promise<any>) | null {
// 将后台路径转换为 ../views 格式
let path = componentPath
// 移除开头的斜杠(如果有)
if (path.startsWith('/')) {
path = path.substring(1)
}
// 补全 .vue 后缀(如果没有)
if (!path.endsWith('.vue')) {
path += '.vue'
}
// 转换为 ../views 格式(匹配 import.meta.glob 的 key
const fullPath = `../views/${path}`
console.log('[Bidding viewLoader] 尝试加载组件:', componentPath, '→', fullPath)
const loader = VIEW_MODULES[fullPath]
if (!loader) {
console.warn('[Bidding viewLoader] 组件未找到:', fullPath)
console.log('[Bidding viewLoader] 可用的组件:', Object.keys(VIEW_MODULES))
return null
}
return loader as () => Promise<any>
}
// Bidding 路由生成器配置
const routeConfig: RouteGeneratorConfig = {
layoutMap: biddingLayoutMap,
viewLoader,
notFoundComponent: () => import('vue').then(({ h }) => ({
default: {
render() { return h('div', { style: { padding: '20px', textAlign: 'center' } }, '404 - 页面未找到') }
}
}))
}
// Bidding 路由生成选项
const routeOptions: GenerateSimpleRoutesOptions = {
asRootChildren: false, // 直接作为根级路由,不是某个布局的子路由
iframePlaceholder: () => import('shared/components').then(m => ({ default: m.IframeView })),
verbose: true // 启用详细日志
}
/**
* 添加动态路由Bidding 特定)
* @param views 视图列表(用作菜单)
*/
export function addDynamicRoutes(views: TbSysViewDTO[]) {
if (!views || views.length === 0) {
console.warn('[Bidding] addDynamicRoutes: 视图列表为空')
return
}
console.log('[Bidding] addDynamicRoutes: 开始添加动态路由,视图数量:', views.length)
console.log('[Bidding] addDynamicRoutes: 路由配置:', routeConfig)
console.log('[Bidding] addDynamicRoutes: 路由选项:', routeOptions)
try {
// 使用 shared 中的通用方法生成路由
const routes = generateSimpleRoutes(views, routeConfig, routeOptions)
// 直接将路由添加到根级别不是作为Root的children
routes.forEach(route => {
console.log('[Bidding] addDynamicRoutes: 添加路由', route.path, '使用布局:', route.component?.name || 'unknown')
router.addRoute(route)
})
} catch (error) {
console.error('[Bidding] addDynamicRoutes: 添加路由失败', error)
throw error
}
}
/**
* 从 LocalStorage 获取菜单并生成路由Bidding 特定)
*
* 使用 shared 中的通用 loadViewsFromStorage 方法
* 筛选出 service='bidding' 的视图
*/
export function loadRoutesFromStorage(): boolean {
try {
console.log('[Bidding] loadRoutesFromStorage: 开始加载动态路由')
// 使用 shared 中的通用方法加载视图数据
const allViews = loadViewsFromStorage('loginDomain', 'userViews')
console.log('[Bidding] loadRoutesFromStorage: 加载的所有视图数量:', allViews?.length || 0)
if (allViews) {
// 过滤出 bidding 服务的视图
const biddingViews = allViews.filter((view: TbSysViewDTO) =>
view.service === 'bidding'
)
console.log('[Bidding] loadRoutesFromStorage: 过滤后的 bidding 视图:', biddingViews)
if (biddingViews.length === 0) {
console.warn('[Bidding] loadRoutesFromStorage: 没有找到 bidding 服务的视图')
return false
}
// 使用 Bidding 的 addDynamicRoutes 添加路由
addDynamicRoutes(biddingViews)
return true
}
console.warn('[Bidding] loadRoutesFromStorage: 未能加载视图数据')
return false
} catch (error) {
console.error('[Bidding] loadRoutesFromStorage: 加载路由失败', error)
return false
}
}

View File

@@ -0,0 +1,94 @@
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
// @ts-ignore
import { TokenManager } from 'shared/api'
// @ts-ignore
import { APP_CONFIG } from 'shared/config'
// @ts-ignore
import { loadRoutesFromStorage } from './dynamicRoute'
// bidding应用的动态路由会根据layout字段自动添加不需要预定义Root布局
const routes: RouteRecordRaw[] = []
const router = createRouter({
history: createWebHistory('/bidding'), // 与nginx保持一致使用/bidding前缀
routes
})
// 标记动态路由是否已加载
let dynamicRoutesLoaded = false
// 路由守卫
router.beforeEach((to, from, next) => {
console.log('[Bidding Router] 路由守卫触发:', {
to: to.path,
from: from.path,
meta: to.meta
})
// 设置页面标题
if (to.meta.title) {
document.title = `${to.meta.title} - 招标管理系统`
}
// 检查是否需要登录
const requiresAuth = to.meta.requiresAuth !== false
const hasToken = TokenManager.hasToken()
console.log('[Bidding Router] 认证检查:', {
requiresAuth,
hasToken,
tokenValue: localStorage.getItem('token')
})
// 其他页面:检查是否需要登录
if (requiresAuth && !hasToken) {
// 需要登录但未登录,重定向到 platform 的登录页
// 重要必须使用完整URL包含origin避免被bidding的路由拦截造成循环
const currentUrl = window.location.href
const origin = window.location.origin
// 构建platform登录页的完整URL
const loginUrl = `${origin}/login?redirect=${encodeURIComponent(currentUrl)}`
console.log('[Bidding Router] 未登录重定向到Platform登录页:', loginUrl)
// 使用完整URL跳转跳出bidding的路由系统
window.location.href = loginUrl
return
}
// 如果已登录且动态路由未加载,先加载动态路由
if (hasToken && !dynamicRoutesLoaded) {
console.log('[Bidding Router] 开始加载动态路由...')
console.log('[Bidding Router] LocalStorage 内容:', {
loginDomain: localStorage.getItem('loginDomain'),
token: localStorage.getItem('token')
})
dynamicRoutesLoaded = true
const loaded = loadRoutesFromStorage?.()
console.log('[Bidding Router] 动态路由加载结果:', loaded)
console.log('[Bidding Router] 当前路径:', to.path)
console.log('[Bidding Router] 所有路由:', router.getRoutes().map(r => r.path))
if (loaded) {
// 动态路由加载成功,重新导航以匹配新添加的路由
console.log('[Bidding Router] 动态路由加载成功,重新导航到:', to.path)
next({ ...to, replace: true })
return
} else {
console.warn('[Bidding Router] 动态路由加载失败')
}
}
console.log('[Bidding Router] 继续正常导航')
next()
})
// 重置动态路由加载状态
export function resetDynamicRoutes() {
dynamicRoutesLoaded = false
}
export default router

View File

@@ -0,0 +1,184 @@
/**
* Shared Module Federation 类型声明
* 用于 TypeScript 识别远程模块
*/
// ========== 组件模块 ==========
declare module 'shared/components' {
export const FileUpload: any
export const DynamicFormItem: any
export const IframeView: any
}
declare module 'shared/components/FileUpload' {
import { DefineComponent } from 'vue'
const FileUpload: DefineComponent<{}, {}, any>
export default FileUpload
}
declare module 'shared/components/DynamicFormItem' {
import { DefineComponent } from 'vue'
const DynamicFormItem: DefineComponent<{}, {}, any>
export default DynamicFormItem
}
declare module 'shared/components/iframe/IframeView.vue' {
import { DefineComponent } from 'vue'
const IframeView: DefineComponent<{}, {}, any>
export default IframeView
}
declare module 'shared/components/iframe/IframeView.vue' {
import { DefineComponent } from 'vue'
const IframeView: DefineComponent<{}, {}, any>
export default IframeView
}
// ========== API 模块 ==========
declare module 'shared/api' {
export const api: any
export const TokenManager: any
}
declare module 'shared/api/auth' {
export const authAPI: any
}
declare module 'shared/api/file' {
export const fileAPI: any
}
declare module 'shared/api' {
export const authAPI: any
export const fileAPI: any
export const TokenManager: any
export const api: any
}
// 保留旧的导出路径(向后兼容)
declare module 'shared/FileUpload' {
import { DefineComponent } from 'vue'
const FileUpload: DefineComponent<{}, {}, any>
export default FileUpload
}
declare module 'shared/DynamicFormItem' {
import { DefineComponent } from 'vue'
const DynamicFormItem: DefineComponent<{}, {}, any>
export default DynamicFormItem
}
declare module 'shared/utils' {
export const initAesEncrypt: any
export const getAesInstance: any
export const formatFileSize: any
export const isImageFile: any
export const getFileTypeIcon: any
export const isValidFileType: any
export const getFilePreviewUrl: any
}
declare module 'shared/types' {
import { RouteRecordRaw } from 'vue-router'
export type LoginParam = any
export type LoginDomain = any
export type SysUserVO = any
export type TbSysFileDTO = any
export type SysConfigVO = any
export type ResultDomain<T = any> = any
// 视图类型(用于路由和菜单)
export interface TbSysViewDTO {
viewId?: string
name?: string
parentId?: string
url?: string
component?: string
service?: string
iframeUrl?: string
icon?: string
type?: number
layout?: string
orderNum?: number
description?: string
children?: TbSysViewDTO[]
}
}
declare module 'shared/utils/route' {
import { RouteRecordRaw } from 'vue-router'
import type { TbSysViewDTO } from 'shared/types'
export interface RouteGeneratorConfig {
layoutMap: Record<string, () => Promise<any>>
viewLoader: (componentPath: string) => (() => Promise<any>) | null
staticRoutes?: RouteRecordRaw[]
notFoundComponent?: () => Promise<any>
}
export interface GenerateSimpleRoutesOptions {
asRootChildren?: boolean
iframePlaceholder?: () => Promise<any>
verbose?: boolean
}
export function generateRoutes(
views: TbSysViewDTO[],
config: RouteGeneratorConfig
): RouteRecordRaw[]
export function generateSimpleRoutes(
views: TbSysViewDTO[],
config: RouteGeneratorConfig,
options?: GenerateSimpleRoutesOptions
): RouteRecordRaw[]
export function buildMenuTree(
views: TbSysViewDTO[],
staticRoutes?: RouteRecordRaw[]
): TbSysViewDTO[]
export function filterMenusByPermissions(
views: TbSysViewDTO[],
permissions: string[]
): TbSysViewDTO[]
export function findMenuByPath(
views: TbSysViewDTO[],
path: string
): TbSysViewDTO | null
export function getMenuPath(
views: TbSysViewDTO[],
targetViewId: string
): TbSysViewDTO[]
export function getFirstAccessibleMenuUrl(
views: TbSysViewDTO[]
): string | null
export function loadViewsFromStorage(
storageKey?: string,
viewsPath?: string
): TbSysViewDTO[] | null
}
declare module 'shared/utils/device' {
export enum DeviceType {
MOBILE = 'mobile',
DESKTOP = 'desktop'
}
export function getDeviceType(): DeviceType
export function isMobile(): boolean
export function isDesktop(): boolean
export function useDevice(): any
}
// ========== Layouts 布局模块 ==========
declare module 'shared/layouts' {
import { DefineComponent } from 'vue'
export const BlankLayout: DefineComponent<{}, {}, any>
}

View File

@@ -7,7 +7,10 @@ import { fileURLToPath } from 'url'
const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
export default defineConfig({
export default defineConfig(({ mode }) => ({
// 开发和生产环境都通过nginx代理访问/bidding
base: '/bidding/',
plugins: [
vue({
script: {
@@ -34,6 +37,7 @@ export default defineConfig({
port: 5002,
host: true,
cors: true,
open: '/bidding/', // 开发时自动打开到 /bidding/ 路径
proxy: {
'/api': {
target: 'http://localhost:8180',
@@ -60,4 +64,4 @@ export default defineConfig({
}
}
}
})
}))

View File

@@ -8,9 +8,6 @@
<!-- 加载运行时配置(必须在其他脚本之前加载) -->
<script src="/app-config.js"></script>
<!-- Module Federation - 预加载远程入口 -->
<link rel="modulepreload" href="http://localhost:5000/remoteEntry.js">
</head>
<body>
<div id="app"></div>

View File

@@ -51,6 +51,13 @@ window.APP_RUNTIME_CONFIG = {
publicImgPath: '/img',
publicWebPath: '/',
// 单点登录配置
sso: {
platformUrl: '/', // platform 平台地址
workcaseUrl: '/workcase', // workcase 服务地址
biddingUrl: '/bidding' // bidding 服务地址
},
// 功能开关
features: {
enableDebug: false,

View File

@@ -135,7 +135,6 @@ function getUserName(): string {
return loginDomain.user?.username || loginDomain.userInfo?.username || '管理员'
}
} catch (error) {
console.error('❌ 获取用户名失败:', error)
}
return '管理员'
}
@@ -149,20 +148,20 @@ function loadMenuFromStorage(): MenuItem[] {
try {
const loginDomainStr = localStorage.getItem('loginDomain')
if (!loginDomainStr) {
console.warn('⚠️ 未找到 loginDomain')
return []
}
const loginDomain = JSON.parse(loginDomainStr)
const userViews = loginDomain.userViews || []
console.log('📋 加载用户视图:', userViews)
// 过滤出 SidebarLayout 的顶级菜单(没有 parentId
// 过滤出 SidebarLayout 的顶级菜单(没有 parentId,且属于 platform 服务且不是admin路由
const sidebarViews = userViews.filter((view: any) =>
view.layout === 'SidebarLayout' &&
!view.parentId &&
view.type === 1 // type 1 是侧边栏菜单
view.type === 1 && // type 1 是侧边栏菜单
view.service === 'platform' && // 只显示 platform 服务的视图
!view.url?.startsWith('/admin') // 排除 admin 路由(由 AdminSidebar 管理)
)
// 按 orderNum 排序
@@ -189,10 +188,8 @@ function loadMenuFromStorage(): MenuItem[] {
}
})
console.log('✅ 侧边栏菜单:', menuItems)
return menuItems
} catch (error) {
console.error('❌ 加载菜单失败:', error)
return []
}
}

View File

@@ -1 +1,3 @@
export { default as SidebarLayout } from "./SidebarLayout/SidebarLayout.vue";
export { default as SidebarLayout } from "./SidebarLayout/SidebarLayout.vue";
// BlankLayout从shared导入
export { BlankLayout } from 'shared/layouts';

View File

@@ -18,43 +18,47 @@ import {
import type { TbSysViewDTO } from 'shared/types'
import type { RouteRecordRaw } from 'vue-router'
import router from './index'
import { SidebarLayout } from '../layouts'
import { SidebarLayout, BlankLayout } from '@/layouts'
// Platform 布局组件映射
const platformLayoutMap: Record<string, () => Promise<any>> = {
'SidebarLayout': () => Promise.resolve({ default: SidebarLayout }),
'BlankLayout': () => Promise.resolve({ default: BlankLayout }),
'NavigationLayout': () => Promise.resolve({ default: SidebarLayout }),
'BasicLayout': () => Promise.resolve({ default: SidebarLayout })
}
// 视图组件加载器
const VIEW_MODULES = import.meta.glob<{ default: any }>('../views/**/*.vue')
const VIEW_MODULES = import.meta.glob<{ default: any }>('@/views/**/*.vue')
/**
* 视图组件加载函数
* @param componentPath 组件路径
* @param componentPath 组件路径(如 "public/Chat/AIChatView.vue"
*/
function viewLoader(componentPath: string): (() => Promise<any>) | null {
// 将后台路径转换为实际路径
// 将后台路径转换为 @/views 格式
let path = componentPath
// 如果不是以 ../ 开头,则认为是相对 views 目录的路径
if (!path.startsWith('../')) {
if (!path.startsWith('/')) {
path = '/' + path
}
path = '../views' + path
// 移除开头的斜杠(如果有)
if (path.startsWith('/')) {
path = path.substring(1)
}
// 补全 .vue 后缀
// 补全 .vue 后缀(如果没有)
if (!path.endsWith('.vue')) {
path += '.vue'
}
const loader = VIEW_MODULES[path]
// 转换为 /src/views 格式(匹配 import.meta.glob 的 key
const fullPath = `/src/views/${path}`
console.log('[Platform viewLoader] 尝试加载组件:', componentPath, '→', fullPath)
const loader = VIEW_MODULES[fullPath]
if (!loader) {
console.warn(`[路由生成] 未找到组件: ${componentPath},期望路径: ${path}`)
console.warn('[Platform viewLoader] 组件未找到:', fullPath)
console.log('[Platform viewLoader] 可用的组件:', Object.keys(VIEW_MODULES))
return null
}
@@ -74,12 +78,8 @@ const routeConfig: RouteGeneratorConfig = {
// Platform 路由生成选项
const routeOptions: GenerateSimpleRoutesOptions = {
asRootChildren: true, // 作为 Root 路由的子路由
iframePlaceholder: () => Promise.resolve({
default: {
template: '<div class="iframe-placeholder"></div>'
}
}),
asRootChildren: false, // 直接作为根级路由,不是某个布局的子路由
iframePlaceholder: () => import('shared/components').then(m => ({ default: m.IframeView })),
verbose: true // 启用详细日志
}
@@ -89,31 +89,34 @@ const routeOptions: GenerateSimpleRoutesOptions = {
*/
export function addDynamicRoutes(views: TbSysViewDTO[]) {
if (!views || views.length === 0) {
console.warn('[Platform 路由] 视图列表为空')
console.warn('[Platform] addDynamicRoutes: 视图列表为空')
return
}
console.log('[Platform 路由] 开始生成路由,视图数量:', views.length)
console.log('[Platform] addDynamicRoutes: 开始添加动态路由,视图数量:', views.length)
try {
// 使用 shared 中的通用方法生成路由
const routes = generateSimpleRoutes(views, routeConfig, routeOptions)
// 将生成的路由添加到 Platform 的 router
// 直接将路由添加到根级别不是作为Root的children
routes.forEach(route => {
router.addRoute('Root', route)
console.log('[Platform 路由] 已添加路由:', {
path: route.path,
name: route.name,
hasComponent: !!route.component,
childrenCount: route.children?.length || 0
})
console.log('[Platform] addDynamicRoutes: 添加路由', route.path, '使用布局:', route.component?.name || 'unknown')
router.addRoute(route)
})
console.log('✅ Platform 动态路由添加完成')
console.log('所有路由:', router.getRoutes().map(r => ({ path: r.path, name: r.name })))
// 动态添加根路径重定向到第一个菜单项
if (routes.length > 0) {
const firstRoute = routes[0]
router.addRoute({
path: '/',
redirect: firstRoute.path
})
console.log('[Platform] addDynamicRoutes: 添加根路径重定向到', firstRoute.path)
}
} catch (error) {
console.error('Platform 动态路由生成失败:', error)
console.error('[Platform] addDynamicRoutes: 添加路由失败', error)
throw error
}
}
@@ -130,18 +133,35 @@ export function addDynamicRoutes(views: TbSysViewDTO[]) {
*/
export function loadRoutesFromStorage(): boolean {
try {
// 使用 shared 中的通用方法加载视图数据
const views = loadViewsFromStorage('loginDomain', 'userViews')
console.log('[Platform] loadRoutesFromStorage: 开始加载动态路由')
if (views) {
// 使用 shared 中的通用方法加载视图数据
const allViews = loadViewsFromStorage('loginDomain', 'userViews')
console.log('[Platform] loadRoutesFromStorage: 加载的所有视图数量:', allViews?.length || 0)
if (allViews) {
// 过滤出 platform 服务的视图
const platformViews = allViews.filter((view: TbSysViewDTO) =>
view.service === 'platform'
)
console.log('[Platform] loadRoutesFromStorage: 过滤后的 platform 视图:', platformViews)
if (platformViews.length === 0) {
console.warn('[Platform] loadRoutesFromStorage: 没有找到 platform 服务的视图')
return false
}
// 使用 Platform 的 addDynamicRoutes 添加路由
addDynamicRoutes(views)
addDynamicRoutes(platformViews)
return true
}
console.warn('[Platform] loadRoutesFromStorage: 未能加载视图数据')
return false
} catch (error) {
console.error('[Platform 路由] 从 LocalStorage 加载路由失败:', error)
console.error('[Platform] loadRoutesFromStorage: 加载路由失败', error)
return false
}
}

View File

@@ -1,15 +1,9 @@
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import { SidebarLayout } from '../layouts'
import { TokenManager } from 'shared/api'
import { loadRoutesFromStorage } from './dynamicRoute'
// platform应用的动态路由会根据layout字段自动添加不需要预定义Root布局
const routes: RouteRecordRaw[] = [
{
path: '/',
name: 'Root',
component: SidebarLayout,
children: []
},
{
path: '/login',
name: 'Login',

View File

@@ -7,6 +7,7 @@
declare module 'shared/components' {
export const FileUpload: any
export const DynamicFormItem: any
export const IframeView: any
}
declare module 'shared/components/FileUpload' {
@@ -21,6 +22,18 @@ declare module 'shared/components/DynamicFormItem' {
export default DynamicFormItem
}
declare module 'shared/components/iframe/IframeView.vue' {
import { DefineComponent } from 'vue'
const IframeView: DefineComponent<{}, {}, any>
export default IframeView
}
declare module 'shared/components/iframe/IframeView.vue' {
import { DefineComponent } from 'vue'
const IframeView: DefineComponent<{}, {}, any>
export default IframeView
}
// ========== API 模块 ==========
declare module 'shared/api' {
export const api: any
@@ -35,6 +48,13 @@ declare module 'shared/api/file' {
export const fileAPI: any
}
declare module 'shared/api' {
export const authAPI: any
export const fileAPI: any
export const TokenManager: any
export const api: any
}
// 保留旧的导出路径(向后兼容)
declare module 'shared/FileUpload' {
import { DefineComponent } from 'vue'
@@ -48,14 +68,6 @@ declare module 'shared/DynamicFormItem' {
export default DynamicFormItem
}
declare module 'shared/authAPI' {
export const authAPI: any
}
declare module 'shared/fileAPI' {
export const fileAPI: any
}
declare module 'shared/utils' {
export const initAesEncrypt: any
export const getAesInstance: any
@@ -83,6 +95,7 @@ declare module 'shared/types' {
parentId?: string
url?: string
component?: string
service?: string
iframeUrl?: string
icon?: string
type?: number
@@ -162,3 +175,10 @@ declare module 'shared/utils/device' {
export function isDesktop(): boolean
export function useDevice(): any
}
// ========== Layouts 布局模块 ==========
declare module 'shared/layouts' {
import { DefineComponent } from 'vue'
export const BlankLayout: DefineComponent<{}, {}, any>
}

View File

@@ -68,9 +68,9 @@ import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import type { LoginParam } from 'shared/types'
import { authAPI } from 'shared/authAPI'
import { getAesInstance } from 'shared/utils'
import { authAPI } from 'shared/api/auth'
import { TokenManager } from 'shared/api'
import { getAesInstance } from 'shared/utils'
import { resetDynamicRoutes } from '@/router'
// 路由

View File

@@ -7,7 +7,11 @@ import { fileURLToPath } from 'url'
const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
export default defineConfig({
// Platform 是根路径应用
base: '/',
plugins: [
vue({
script: {
@@ -50,6 +54,7 @@ export default defineConfig({
port: 5001,
host: true,
cors: true,
open: '/', // 开发时自动打开到根路径
proxy: {
'/api': {
target: 'http://localhost:8180',

View File

@@ -0,0 +1,90 @@
<template>
<div class="iframe-view">
<iframe
v-if="iframeUrl"
:src="iframeUrl"
class="iframe-content"
frameborder="0"
@load="handleLoad"
/>
<div v-else class="iframe-error">
<el-icon class="error-icon"><WarningFilled /></el-icon>
<p>无效的 iframe 地址</p>
</div>
<div v-if="loading" class="iframe-loading">
<el-icon class="is-loading"><Loading /></el-icon>
<span>加载中...</span>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { Loading, WarningFilled } from '@element-plus/icons-vue'
const route = useRoute()
const loading = ref(true)
// 从路由 meta 中获取 iframe URL
const iframeUrl = computed(() => {
return route.meta.iframeUrl as string || ''
})
function handleLoad() {
loading.value = false
}
onMounted(() => {
console.log('[IframeView] 加载 iframe:', iframeUrl.value)
})
</script>
<style lang="scss" scoped>
.iframe-view {
position: relative;
width: 100%;
height: 100%;
overflow: hidden;
}
.iframe-content {
width: 100%;
height: 100%;
border: none;
}
.iframe-error {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100%;
color: var(--el-text-color-secondary);
.error-icon {
font-size: 48px;
margin-bottom: 16px;
color: var(--el-color-warning);
}
}
.iframe-loading {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
background: var(--el-bg-color);
gap: 12px;
.el-icon {
font-size: 32px;
color: var(--el-color-primary);
}
}
</style>

View File

@@ -1,3 +1,6 @@
export * from './fileupload'
export * from './base'
export * from './dynamicFormItem'
export * from './dynamicFormItem'
// 通用视图组件
export { default as IframeView } from './iframe/IframeView.vue'

View File

@@ -43,6 +43,12 @@ export interface AppRuntimeConfig {
};
publicImgPath: string;
publicWebPath: string;
// 单点登录配置
sso?: {
platformUrl: string; // platform 平台地址
workcaseUrl: string; // workcase 服务地址
biddingUrl: string; // bidding 服务地址
};
features?: {
enableDebug?: boolean;
enableMockData?: boolean;
@@ -92,6 +98,15 @@ const devConfig: AppRuntimeConfig = {
publicImgPath: 'http://localhost:5173/img',
publicWebPath: 'http://localhost:5173',
// 单点登录配置
// 推荐开发环境也通过nginx访问http://localhost
// 备选直接访问各服务端口platformUrl: 'http://localhost:5001'
sso: {
platformUrl: '/', // 通过nginx访问platform
workcaseUrl: '/workcase', // 通过nginx访问workcase
biddingUrl: '/bidding' // 通过nginx访问bidding
},
features: {
enableDebug: true,
enableMockData: false
@@ -132,6 +147,13 @@ const prodDefaultConfig: AppRuntimeConfig = {
publicImgPath: '/img',
publicWebPath: '/',
// 单点登录配置生产环境通过nginx代理
sso: {
platformUrl: '/',
workcaseUrl: '/workcase',
biddingUrl: '/bidding'
},
features: {
enableDebug: false,
enableMockData: false
@@ -218,6 +240,13 @@ export const APP_CONFIG = {
publicImgPath: config.publicImgPath,
publicWebPath: config.publicWebPath,
// 单点登录配置
sso: config.sso || {
platformUrl: '/',
workcaseUrl: '/workcase',
biddingUrl: '/bidding'
},
// 功能开关
features: config.features || {}
};

View File

@@ -0,0 +1,18 @@
<template>
<div class="blank-layout">
<router-view />
</div>
</template>
<script setup lang="ts">
// BlankLayout空白布局只显示内容无侧边栏、无header
// 适用于全屏页面,如聊天页面、独立功能页等
</script>
<style scoped lang="scss">
.blank-layout {
width: 100%;
height: 100vh;
overflow: hidden;
}
</style>

View File

@@ -0,0 +1 @@
export { default as BlankLayout } from './BlankLayout/BlankLayout.vue'

View File

@@ -128,6 +128,8 @@ export interface TbSysViewDTO extends BaseDTO {
type?: number;
/** 视图类型 route\iframe*/
viewType?: string;
/** 所属服务 platform\workcase\bidding */
service?: string;
/** 布局 */
layout?: string;
/** 排序 */

View File

@@ -184,15 +184,22 @@ function generateRouteFromMenu(
route.component = component
} else {
// 组件加载失败,使用 404
route.component = config.notFoundComponent || (() => Promise.resolve({ default: { template: '<div>404</div>' } }))
route.component = config.notFoundComponent || (() => import('vue').then(({ h }) => ({
default: {
render() { return h('div', '404') }
}
})))
}
} else {
// 使用路由占位组件
route.component = () => Promise.resolve({
route.component = () => import('vue').then(({ h, resolveComponent }) => ({
default: {
template: '<router-view />'
render() {
const RouterView = resolveComponent('RouterView')
return h(RouterView)
}
}
})
}))
}
}
@@ -677,17 +684,29 @@ function generateSimpleRoute(
let component: any
if (isIframe) {
// iframe 类型:使用占位组件
component = iframePlaceholder || (() => Promise.resolve({
default: {
template: '<div class="iframe-placeholder"></div>'
}
}))
// iframe 类型:使用占位组件用于显示iframe内容
// 路由路径使用 url 字段(应该设置为不冲突的路径,如 /app/workcase
component = iframePlaceholder || (() => import('vue').then(({ h }) => ({
default: {
render() { return h('div', { class: 'iframe-placeholder' }, 'Loading...') }
}
})))
} else if (view.component) {
// route 类型:加载实际组件
component = config.viewLoader(view.component)
if (!component) {
if (verbose) console.warn('[路由生成] 组件加载失败:', view.component)
if (verbose) console.warn('[路由生成] 组件加载失败:', view.component, '使用占位组件')
// 使用占位组件,避免路由无效
const errorMsg = `组件加载失败: ${view.component}`
component = () => import('vue').then(({ h }) => ({
default: {
render() {
return h('div', {
style: { padding: '20px', color: 'red' }
}, errorMsg)
}
}
}))
}
}
@@ -753,11 +772,14 @@ function generateSimpleRoute(
route.component = component
} else if (!component && hasChildren) {
// 没有组件,只有子视图(路由容器)
route.component = () => Promise.resolve({
route.component = () => import('vue').then(({ h, resolveComponent }) => ({
default: {
template: '<router-view />'
render() {
const RouterView = resolveComponent('RouterView')
return h(RouterView)
}
}
})
}))
route.children = []
// 添加子路由
@@ -785,5 +807,51 @@ function generateSimpleRoute(
return null
}
// 处理layout如果视图指定了layout且不是作为Root的子路由且有有效组件需要包裹layout
const viewLayout = (view as any).layout
if (viewLayout && !asRootChild && route.component && config.layoutMap[viewLayout]) {
if (verbose) {
console.log('[路由生成] 为视图添加布局:', view.name, '布局:', viewLayout, '路径:', routePath)
}
// 创建layout路由将原路由的组件作为其子路由
const layoutRoute: RouteRecordRaw = {
path: routePath,
name: view.viewId,
component: config.layoutMap[viewLayout],
meta: {
...route.meta,
layout: viewLayout // 标记使用的布局
},
children: [
{
path: '',
name: `${view.viewId}_content`,
component: route.component,
meta: route.meta
}
]
}
// 如果原路由有其他children子视图也添加到layout路由的children中
if (route.children && route.children.length > 0) {
// 跳过第一个空路径的子路由(如果存在)
const otherChildren = route.children.filter((child: any) => child.path !== '')
if (otherChildren.length > 0) {
layoutRoute.children!.push(...otherChildren)
}
}
if (verbose) {
console.log('[路由生成] Layout路由生成完成:', {
path: layoutRoute.path,
name: layoutRoute.name,
childrenCount: layoutRoute.children?.length
})
}
return layoutRoute
}
return route
}

View File

@@ -36,7 +36,8 @@ export default defineConfig({
'./components': './src/components/index.ts',
'./components/FileUpload': './src/components/fileupload/FileUpload.vue',
'./components/DynamicFormItem': './src/components/dynamicFormItem/DynamicFormItem.vue',
'./components/iframe/IframeView.vue': './src/components/iframe/IframeView.vue',
// ========== API 模块 ==========
'./api': './src/api/index.ts',
'./api/auth': './src/api/auth/auth.ts',
@@ -54,7 +55,13 @@ export default defineConfig({
'./types/base': './src/types/base/index.ts',
'./types/auth': './src/types/auth/index.ts',
'./types/file': './src/types/file/index.ts',
'./types/sys': './src/types/sys/index.ts'
'./types/sys': './src/types/sys/index.ts',
// ========== Config 配置模块 ==========
'./config': './src/config/index.ts',
// ========== Layouts 布局模块 ==========
'./layouts': './src/layouts/index.ts'
},
// 共享依赖(重要:避免重复加载)
shared: {

View File

@@ -4,100 +4,30 @@
import {loadShare} from "@module-federation/runtime";
const importMap = {
"@element-plus/icons-vue": async () => {
let pkg = await import("__mf__virtual/shared__prebuild___mf_0_element_mf_2_plus_mf_1_icons_mf_2_vue__prebuild__.js");
return pkg;
}
,
"axios": async () => {
let pkg = await import("__mf__virtual/shared__prebuild__axios__prebuild__.js");
return pkg;
}
,
"element-plus": async () => {
let pkg = await import("__mf__virtual/shared__prebuild__element_mf_2_plus__prebuild__.js");
let pkg = await import("__mf__virtual/workcase__prebuild__element_mf_2_plus__prebuild__.js");
return pkg;
}
,
"vue": async () => {
let pkg = await import("__mf__virtual/shared__prebuild__vue__prebuild__.js");
let pkg = await import("__mf__virtual/workcase__prebuild__vue__prebuild__.js");
return pkg;
}
,
"vue-router": async () => {
let pkg = await import("__mf__virtual/shared__prebuild__vue_mf_2_router__prebuild__.js");
let pkg = await import("__mf__virtual/workcase__prebuild__vue_mf_2_router__prebuild__.js");
return pkg;
}
}
const usedShared = {
"@element-plus/icons-vue": {
name: "@element-plus/icons-vue",
version: "2.3.2",
scope: ["default"],
loaded: false,
from: "shared",
async get () {
if (false) {
throw new Error(`Shared module '${"@element-plus/icons-vue"}' must be provided by host`);
}
usedShared["@element-plus/icons-vue"].loaded = true
const {"@element-plus/icons-vue": pkgDynamicImport} = importMap
const res = await pkgDynamicImport()
const exportModule = {...res}
// All npm packages pre-built by vite will be converted to esm
Object.defineProperty(exportModule, "__esModule", {
value: true,
enumerable: false
})
return function () {
return exportModule
}
},
shareConfig: {
singleton: false,
requiredVersion: "^2.3.2",
}
}
,
"axios": {
name: "axios",
version: "1.13.2",
scope: ["default"],
loaded: false,
from: "shared",
async get () {
if (false) {
throw new Error(`Shared module '${"axios"}' must be provided by host`);
}
usedShared["axios"].loaded = true
const {"axios": pkgDynamicImport} = importMap
const res = await pkgDynamicImport()
const exportModule = {...res}
// All npm packages pre-built by vite will be converted to esm
Object.defineProperty(exportModule, "__esModule", {
value: true,
enumerable: false
})
return function () {
return exportModule
}
},
shareConfig: {
singleton: false,
requiredVersion: "^1.13.2",
}
}
,
"element-plus": {
name: "element-plus",
version: "2.12.0",
scope: ["default"],
loaded: false,
from: "shared",
from: "workcase",
async get () {
if (false) {
throw new Error(`Shared module '${"element-plus"}' must be provided by host`);
@@ -127,7 +57,7 @@
version: "3.5.25",
scope: ["default"],
loaded: false,
from: "shared",
from: "workcase",
async get () {
if (false) {
throw new Error(`Shared module '${"vue"}' must be provided by host`);
@@ -157,7 +87,7 @@
version: "4.6.3",
scope: ["default"],
loaded: false,
from: "shared",
from: "workcase",
async get () {
if (false) {
throw new Error(`Shared module '${"vue-router"}' must be provided by host`);
@@ -184,6 +114,14 @@
}
const usedRemotes = [
{
entryGlobalName: "shared",
name: "shared",
type: "module",
entry: "http://localhost:5000/remoteEntry.js",
shareScope: "default",
}
]
export {
usedShared,

View File

@@ -8,23 +8,6 @@
<!-- 加载运行时配置(必须在其他脚本之前加载) -->
<script src="/app-config.js"></script>
<!-- Import Maps 配置 - 引用共享模块 -->
<script type="importmap">
{
"imports": {
"@shared/components": "http://localhost:5000/shared/components.js",
"@shared/utils": "http://localhost:5000/shared/utils.js",
"@shared/api": "http://localhost:5000/shared/api.js",
"@shared/composables": "http://localhost:5000/shared/composables.js",
"@shared/types": "http://localhost:5000/shared/types.js"
}
}
</script>
<!-- 预加载关键模块 -->
<link rel="modulepreload" href="http://localhost:5000/shared/components.js">
<link rel="modulepreload" href="http://localhost:5000/shared/utils.js">
</head>
<body>
<div id="app"></div>

View File

@@ -21,6 +21,7 @@
"@types/node": "^22.0.0",
"@vitejs/plugin-vue": "^5.2.1",
"@vitejs/plugin-vue-jsx": "^4.1.1",
"@module-federation/vite": "^1.9.3",
"typescript": "^5.7.2",
"vite": "^6.0.3",
"vue-tsc": "^2.2.0"

View File

@@ -28,6 +28,9 @@ dependencies:
version: 4.6.3(vue@3.5.25)
devDependencies:
'@module-federation/vite':
specifier: ^1.9.3
version: 1.9.3
'@types/node':
specifier: ^22.0.0
version: 22.19.1
@@ -596,10 +599,61 @@ packages:
'@jridgewell/sourcemap-codec': 1.5.5
dev: true
/@module-federation/error-codes@0.21.6:
resolution: {integrity: sha512-MLJUCQ05KnoVl8xd6xs9a5g2/8U+eWmVxg7xiBMeR0+7OjdWUbHwcwgVFatRIwSZvFgKHfWEiI7wsU1q1XbTRQ==}
dev: true
/@module-federation/runtime-core@0.21.6:
resolution: {integrity: sha512-5Hd1Y5qp5lU/aTiK66lidMlM/4ji2gr3EXAtJdreJzkY+bKcI5+21GRcliZ4RAkICmvdxQU5PHPL71XmNc7Lsw==}
dependencies:
'@module-federation/error-codes': 0.21.6
'@module-federation/sdk': 0.21.6
dev: true
/@module-federation/runtime@0.21.6:
resolution: {integrity: sha512-+caXwaQqwTNh+CQqyb4mZmXq7iEemRDrTZQGD+zyeH454JAYnJ3s/3oDFizdH6245pk+NiqDyOOkHzzFQorKhQ==}
dependencies:
'@module-federation/error-codes': 0.21.6
'@module-federation/runtime-core': 0.21.6
'@module-federation/sdk': 0.21.6
dev: true
/@module-federation/sdk@0.21.6:
resolution: {integrity: sha512-x6hARETb8iqHVhEsQBysuWpznNZViUh84qV2yE7AD+g7uIzHKiYdoWqj10posbo5XKf/147qgWDzKZoKoEP2dw==}
dev: true
/@module-federation/vite@1.9.3:
resolution: {integrity: sha512-MV6XI3FX6okEMJ7FdmvFmYuu7DygRoLljKT8atrBwFhlttsgBbswpqMj4P4Fs/X+pFmbIi/ntFzVhsrG0qQnGQ==}
dependencies:
'@module-federation/runtime': 0.21.6
'@module-federation/sdk': 0.21.6
'@rollup/pluginutils': 5.3.0
defu: 6.1.4
estree-walker: 2.0.2
magic-string: 0.30.21
pathe: 1.1.2
transitivePeerDependencies:
- rollup
dev: true
/@rolldown/pluginutils@1.0.0-beta.53:
resolution: {integrity: sha512-vENRlFU4YbrwVqNDZ7fLvy+JR1CRkyr01jhSiDpE1u6py3OMzQfztQU2jxykW3ALNxO4kSlqIDeYyD0Y9RcQeQ==}
dev: true
/@rollup/pluginutils@5.3.0:
resolution: {integrity: sha512-5EdhGZtnu3V88ces7s53hhfK5KSASnJZv8Lulpc04cWO3REESroJXg73DFsOmgbU2BhwV0E20bu2IDZb3VKW4Q==}
engines: {node: '>=14.0.0'}
peerDependencies:
rollup: ^1.20.0||^2.0.0||^3.0.0||^4.0.0
peerDependenciesMeta:
rollup:
optional: true
dependencies:
'@types/estree': 1.0.8
estree-walker: 2.0.2
picomatch: 4.0.3
dev: true
/@rollup/rollup-android-arm-eabi@4.53.3:
resolution: {integrity: sha512-mRSi+4cBjrRLoaal2PnqH82Wqyb+d3HsPUN/W+WslCXsZsyHa9ZeQQX/pQsZaVIWDkPcpV6jJ+3KLbTbgnwv8w==}
cpu: [arm]
@@ -1146,6 +1200,10 @@ packages:
ms: 2.1.3
dev: true
/defu@6.1.4:
resolution: {integrity: sha512-mEQCMmwJu317oSz8CwdIOdwf3xMif1ttiM8LTufzc3g6kR+9Pe236twL8j3IYT1F7GfRgGcW6MWxzZjLIkuHIg==}
dev: true
/delayed-stream@1.0.0:
resolution: {integrity: sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==}
engines: {node: '>=0.4.0'}
@@ -1464,6 +1522,10 @@ packages:
resolution: {integrity: sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g==}
dev: true
/pathe@1.1.2:
resolution: {integrity: sha512-whLdWMYL2TwI08hn8/ZqAbrVemu0LNaNNJZX73O6qaIdCTfXutsLhMkjdENX0qhsQ9uIimo4/aQOmXkoon2nDQ==}
dev: true
/picocolors@1.1.1:
resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==}

View File

@@ -51,6 +51,13 @@ window.APP_RUNTIME_CONFIG = {
publicImgPath: '/img',
publicWebPath: '/',
// 单点登录配置
sso: {
platformUrl: '/', // platform 平台地址
workcaseUrl: '/workcase', // workcase 服务地址
biddingUrl: '/bidding' // bidding 服务地址
},
// 功能开关
features: {
enableDebug: false,

View File

@@ -0,0 +1,8 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
<circle cx="50" cy="50" r="50" fill="#ffe4c4"/>
<circle cx="50" cy="38" r="18" fill="#ffd1a1"/>
<ellipse cx="50" cy="75" rx="28" ry="20" fill="#ff6b6b"/>
<circle cx="38" cy="35" r="3" fill="#333"/>
<circle cx="62" cy="35" r="3" fill="#333"/>
<path d="M42 48 Q50 55 58 48" stroke="#333" stroke-width="2" fill="none"/>
</svg>

After

Width:  |  Height:  |  Size: 399 B

View File

@@ -0,0 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
<rect width="100" height="100" rx="20" fill="#7c3aed"/>
<path d="M30 70V40h10v30H30zm15-30h10v30H45V40zm15 0h10v30H60V40z" fill="white"/>
<rect x="25" y="30" width="50" height="5" rx="2" fill="white"/>
</svg>

After

Width:  |  Height:  |  Size: 278 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

View File

@@ -0,0 +1,27 @@
<template>
<router-view />
</template>
<script setup lang="ts">
import { onMounted } from 'vue'
onMounted(() => {
console.log('✅ Workcase App Mounted')
})
</script>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
#app {
width: 100%;
height: 100vh;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
</style>

View File

@@ -0,0 +1,34 @@
/**
* Workcase 应用配置
*/
/**
* AES 加密密钥(与后端保持一致)
* 对应后端配置security.aes.secret-key
* Base64 编码的 32 字节密钥256 位)
*/
export const AES_SECRET_KEY = 'MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI=' // Base64 编码,解码后是 "12345678901234567890123456789012" (32字节)
/**
* API 基础地址
* 注意:使用 shared 的 APP_CONFIG 统一管理,这里保留用于特殊场景
*/
export const API_BASE_URL = (import.meta as any).env?.VITE_API_BASE_URL || '/api'
/**
* Platform URL单点登录入口
* 开发环境:
* - 通过nginx访问时使用 '/'(推荐)
* - 直接访问各服务时使用 'http://localhost:5001'
* 生产环境:统一使用 '/'
*/
export const PLATFORM_URL = (import.meta as any).env?.VITE_PLATFORM_URL || '/'
/**
* 应用配置
*/
export const APP_CONFIG = {
name: '泰豪小电',
version: '1.0.0',
copyright: '泰豪电源'
}

View File

@@ -0,0 +1,264 @@
.sidebar-layout {
display: flex;
width: 100%;
height: 100vh;
overflow: hidden;
}
// ==================== 侧边栏 ====================
.sidebar {
width: 220px;
height: 100%;
background: #F0EAF4;
display: flex;
flex-direction: column;
color: #333;
flex-shrink: 0;
transition: width 0.3s ease;
border-right: 1px solid rgba(0, 0, 0, 0.08);
&.collapsed {
width: 64px;
.sidebar-header {
padding: 16px 12px;
justify-content: center;
.logo {
justify-content: center;
}
.collapse-btn {
position: static;
margin-left: 0;
}
}
.nav-item {
justify-content: center;
padding: 12px;
}
.user-section {
justify-content: center;
padding: 16px 12px;
}
}
}
// 侧边栏头部
.sidebar-header {
padding: 16px 20px;
border-bottom: 1px solid rgba(0, 0, 0, 0.08);
display: flex;
align-items: center;
justify-content: space-between;
}
.collapse-btn {
width: 28px;
height: 28px;
display: flex;
align-items: center;
justify-content: center;
border-radius: 6px;
cursor: pointer;
color: #888;
transition: all 0.2s;
&:hover {
background: rgba(124, 58, 237, 0.1);
color: #7c3aed;
}
}
.logo {
display: flex;
align-items: center;
gap: 10px;
.logo-img {
width: 40px;
height: 40px;
border-radius: 6px;
object-fit: contain;
background: #fff;
padding: 2px;
}
.logo-text {
font-size: 16px;
font-weight: 600;
color: #333;
}
}
// 导航菜单
.nav-menu {
flex: 1;
overflow-y: auto;
padding: 12px 0;
&::-webkit-scrollbar {
width: 4px;
}
&::-webkit-scrollbar-thumb {
background: rgba(0, 0, 0, 0.2);
border-radius: 4px;
}
}
.nav-section {
padding: 8px 0;
}
.nav-item {
display: flex;
align-items: center;
gap: 12px;
padding: 14px 20px;
margin-bottom: 4px;
cursor: pointer;
transition: all 0.2s ease;
color: #555;
font-size: 14px;
&:hover {
background: rgba(124, 58, 237, 0.1);
color: #7c3aed;
}
&.active {
background: rgba(124, 58, 237, 0.15);
color: #7c3aed;
font-weight: 500;
}
.el-icon {
font-size: 18px;
flex-shrink: 0;
}
span {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
}
// 用户信息
.user-section {
padding: 16px 20px;
border-top: 1px solid rgba(0, 0, 0, 0.08);
cursor: pointer;
transition: background 0.2s;
&:hover {
background: rgba(124, 58, 237, 0.05);
}
.user-info-wrapper {
display: flex;
align-items: center;
gap: 12px;
}
.user-avatar {
flex-shrink: 0;
}
.user-name {
font-size: 14px;
font-weight: 500;
color: #333;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
}
// ==================== 主内容区 ====================
.main-content {
flex: 1;
height: 100%;
overflow: hidden;
background: #fff;
position: relative;
}
// iframe 容器
.iframe-container {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
position: relative;
}
.iframe-header {
height: 56px;
padding: 0 24px;
display: flex;
align-items: center;
justify-content: space-between;
border-bottom: 1px solid #e5e7eb;
background: #fafafa;
flex-shrink: 0;
}
.iframe-title {
font-size: 16px;
font-weight: 600;
color: #333;
}
.content-iframe {
flex: 1;
width: 100%;
height: 100%;
border: none;
background: #fff;
}
.iframe-loading {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
display: flex;
flex-direction: column;
align-items: center;
gap: 12px;
color: #7c3aed;
font-size: 14px;
z-index: 10;
.el-icon {
font-size: 32px;
}
}
// ==================== 响应式 ====================
@media (max-width: 768px) {
.sidebar {
width: 64px;
&:not(.collapsed) {
width: 220px;
position: fixed;
left: 0;
top: 0;
z-index: 1000;
box-shadow: 2px 0 8px rgba(0, 0, 0, 0.1);
}
}
.iframe-header {
padding: 0 16px;
.iframe-title {
font-size: 14px;
}
}
}

View File

@@ -0,0 +1,293 @@
<template>
<div class="sidebar-layout">
<!-- 侧边栏 -->
<aside class="sidebar" :class="{ collapsed: collapsed }">
<div class="sidebar-header">
<div class="logo">
<img src="/logo.jpg" alt="Logo" class="logo-img" />
<span v-if="!collapsed" class="logo-text">城市生命线</span>
</div>
<div class="collapse-btn" @click="toggleSidebar">
<el-icon>
<DArrowLeft v-if="!collapsed" />
<DArrowRight v-else />
</el-icon>
</div>
</div>
<nav class="nav-menu">
<div class="nav-section">
<div
v-for="item in menuItems"
:key="item.key"
class="nav-item"
:class="{ active: activeMenu === item.key }"
@click="handleMenuClick(item)"
>
<el-icon><component :is="item.icon" /></el-icon>
<span v-if="!collapsed">{{ item.label }}</span>
</div>
</div>
</nav>
<!-- 用户信息 -->
<el-dropdown class="user-section" trigger="click" @command="handleUserCommand">
<div class="user-info-wrapper">
<div class="user-avatar">
<el-avatar :size="36" src="/avatar.svg" @error="handleAvatarError" />
</div>
<span v-if="!collapsed" class="user-name">{{ userName }}</span>
</div>
<template #dropdown>
<el-dropdown-menu>
<el-dropdown-item command="profile">
<el-icon><User /></el-icon>
个人中心
</el-dropdown-item>
<el-dropdown-item command="settings" divided>
<el-icon><Setting /></el-icon>
系统设置
</el-dropdown-item>
<el-dropdown-item command="logout" divided>
<el-icon><SwitchButton /></el-icon>
退出登录
</el-dropdown-item>
</el-dropdown-menu>
</template>
</el-dropdown>
</aside>
<!-- 主内容区 -->
<main class="main-content">
<!-- iframe 模式 -->
<div v-if="currentIframeUrl" class="iframe-container">
<div class="iframe-header">
<span class="iframe-title">{{ currentMenuItem?.label }}</span>
<el-button
text
@click="handleRefreshIframe"
:icon="Refresh"
>
刷新
</el-button>
</div>
<iframe
ref="iframeRef"
:src="currentIframeUrl"
class="content-iframe"
frameborder="0"
@load="handleIframeLoad"
/>
<div v-if="iframeLoading" class="iframe-loading">
<el-icon class="is-loading"><Loading /></el-icon>
<span>加载中...</span>
</div>
</div>
<!-- 路由模式 -->
<router-view v-else />
</main>
</div>
</template>
<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import {
ChatDotRound,
Grid,
Connection,
Document,
Service,
DArrowLeft,
DArrowRight,
User,
Setting,
SwitchButton,
Refresh,
Loading
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
interface MenuItem {
key: string
label: string
icon: string
url?: string
type: 'route' | 'iframe'
}
const router = useRouter()
const route = useRoute()
// 状态管理
const collapsed = ref(false)
const activeMenu = ref('home')
const iframeLoading = ref(false)
const iframeRef = ref<HTMLIFrameElement>()
// 从 LocalStorage 获取用户名
function getUserName(): string {
try {
const loginDomainStr = localStorage.getItem('loginDomain')
if (loginDomainStr) {
const loginDomain = JSON.parse(loginDomainStr)
return loginDomain.user?.username || loginDomain.userInfo?.username || '管理员'
}
} catch (error) {
console.error('❌ 获取用户名失败:', error)
}
return '管理员'
}
const userName = ref(getUserName())
/**
* 从 LocalStorage 加载菜单
*/
function loadMenuFromStorage(): MenuItem[] {
try {
const loginDomainStr = localStorage.getItem('loginDomain')
if (!loginDomainStr) {
console.warn('⚠️ 未找到 loginDomain')
return []
}
const loginDomain = JSON.parse(loginDomainStr)
const userViews = loginDomain.userViews || []
console.log('📋 加载用户视图:', userViews)
// 过滤出 SidebarLayout 的顶级菜单(没有 parentId且属于 workcase 服务且不是admin路由
const sidebarViews = userViews.filter((view: any) =>
view.layout === 'SidebarLayout' &&
!view.parentId &&
view.type === 1 && // type 1 是侧边栏菜单
view.service === 'workcase' && // 只显示 workcase 服务的视图
!view.url?.startsWith('/admin') // 排除 admin 路由(由 AdminSidebar 管理)
)
console.log('🔍 过滤后的 workcase 视图:', sidebarViews)
// 按 orderNum 排序
sidebarViews.sort((a: any, b: any) => (a.orderNum || 0) - (b.orderNum || 0))
// 转换为 MenuItem 格式
const menuItems: MenuItem[] = sidebarViews.map((view: any) => {
// 根据 viewType 或 iframeUrl 判断是 route 还是 iframe
const isIframe = view.viewType === 'iframe' || !!view.iframeUrl
// 确定菜单的路由路径
let menuUrl = view.url
if (isIframe && view.url && (view.url.startsWith('http://') || view.url.startsWith('https://'))) {
// iframe 类型且 url 是外部链接,使用 viewId 作为路由路径
menuUrl = `/${view.viewId}`
}
return {
key: view.viewId || view.name,
label: view.name,
icon: view.icon || 'Grid',
url: menuUrl,
type: isIframe ? 'iframe' : 'route'
}
})
console.log('✅ 侧边栏菜单:', menuItems)
return menuItems
} catch (error) {
console.error('❌ 加载菜单失败:', error)
return []
}
}
// 菜单配置(从 LocalStorage 加载)
const menuItems = ref<MenuItem[]>(loadMenuFromStorage())
// 当前菜单项
const currentMenuItem = computed(() => {
return menuItems.value.find(item => item.key === activeMenu.value)
})
// 当前 iframe URL从路由 meta 读取)
const currentIframeUrl = computed(() => {
const meta = route.meta as any
return meta?.iframeUrl || null
})
// 切换侧边栏
const toggleSidebar = () => {
collapsed.value = !collapsed.value
}
// 处理菜单点击
const handleMenuClick = (item: MenuItem) => {
activeMenu.value = item.key
// 所有菜单都通过路由跳转
if (item.url) {
router.push(item.url)
if (item.type === 'iframe') {
iframeLoading.value = true
}
}
}
// iframe 加载完成
const handleIframeLoad = () => {
iframeLoading.value = false
}
// 刷新 iframe
const handleRefreshIframe = () => {
if (iframeRef.value) {
iframeLoading.value = true
iframeRef.value.src = iframeRef.value.src
}
}
// 用户头像加载错误
const handleAvatarError = () => {
return true
}
// 用户操作
const handleUserCommand = (command: string) => {
switch (command) {
case 'profile':
router.push('/profile')
break
case 'settings':
router.push('/settings')
break
case 'logout':
localStorage.clear()
ElMessage.success('退出成功')
router.push('/login')
break
}
}
// 监听路由变化,同步激活菜单
watch(
() => route.path,
(newPath) => {
// 查找匹配的菜单项route 或 iframe 类型)
const menuItem = menuItems.value.find((item: MenuItem) => item.url === newPath)
if (menuItem) {
activeMenu.value = menuItem.key
} else {
// 如果路径不匹配,尝试通过 route.name 匹配 viewId
const menuByName = menuItems.value.find((item: MenuItem) => item.key === route.name)
if (menuByName) {
activeMenu.value = menuByName.key
}
}
},
{ immediate: true }
)
</script>
<style lang="scss" scoped>
@import url("./SidebarLayout.scss");
</style>

View File

@@ -0,0 +1,3 @@
export { default as SidebarLayout } from './SidebarLayout/SidebarLayout.vue'
// BlankLayout从shared导入
export { BlankLayout } from 'shared/layouts'

View File

@@ -0,0 +1,48 @@
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import ElementPlus from 'element-plus'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import 'element-plus/dist/index.css'
import App from './App.vue'
import router from './router/'
import { AES_SECRET_KEY } from './config'
// @ts-ignore
import { initAesEncrypt } from 'shared/utils'
// 异步初始化应用
async function initApp() {
// 1. 初始化 AES 加密工具
try {
await initAesEncrypt(AES_SECRET_KEY)
console.log('✅ AES 加密工具初始化成功')
} catch (error) {
console.error('❌ AES 加密工具初始化失败:', error)
}
// 2. 创建 Vue 应用
const app = createApp(App)
// 3. 注册 Pinia
const pinia = createPinia()
app.use(pinia)
// 4. 注册 Element Plus
app.use(ElementPlus)
// 5. 注册所有 Element Plus 图标
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
app.component(key, component)
}
// 6. 注册路由
app.use(router)
// 7. 挂载应用
app.mount('#app')
console.log('✅ Workcase 应用启动成功')
}
// 启动应用
initApp()

View File

@@ -0,0 +1,154 @@
/**
* 动态路由生成模块Workcase 特定)
*
* 职责:
* 1. 提供 Workcase 特定的布局和组件配置
* 2. 调用 shared 中的通用路由生成方法
* 3. 将生成的路由添加到 Workcase 的 router 实例
*/
/// <reference types="vite/client" />
import {
generateSimpleRoutes,
loadViewsFromStorage,
type RouteGeneratorConfig,
type GenerateSimpleRoutesOptions
} from 'shared/utils/route'
import type { TbSysViewDTO } from 'shared/types'
import type { RouteRecordRaw } from 'vue-router'
import router from './index'
import { SidebarLayout, BlankLayout } from '@/layouts'
// Workcase 布局组件映射
const workcaseLayoutMap: Record<string, () => Promise<any>> = {
'SidebarLayout': () => Promise.resolve({ default: SidebarLayout }),
'BlankLayout': () => Promise.resolve({ default: BlankLayout }),
'NavigationLayout': () => Promise.resolve({ default: SidebarLayout }),
'BasicLayout': () => Promise.resolve({ default: SidebarLayout })
}
// 视图组件加载器
const VIEW_MODULES = import.meta.glob<{ default: any }>('../views/**/*.vue')
/**
* 视图组件加载函数
* @param componentPath 组件路径(如 "public/AIChat/AIChatView.vue" 或 "workcase/List"
*/
function viewLoader(componentPath: string): (() => Promise<any>) | null {
// 将后台路径转换为 @/views 格式
let path = componentPath
// 移除开头的斜杠(如果有)
if (path.startsWith('/')) {
path = path.substring(1)
}
// 补全 .vue 后缀(如果没有)
if (!path.endsWith('.vue')) {
path += '.vue'
}
// 转换为 ../views 格式(匹配 import.meta.glob 的 key
const fullPath = `../views/${path}`
console.log('[Workcase viewLoader] 尝试加载组件:', componentPath, '→', fullPath)
const loader = VIEW_MODULES[fullPath]
if (!loader) {
console.warn('[Workcase viewLoader] 组件未找到:', fullPath)
console.log('[Workcase viewLoader] 可用的组件:', Object.keys(VIEW_MODULES))
return null
}
return loader as () => Promise<any>
}
// Workcase 路由生成器配置
const routeConfig: RouteGeneratorConfig = {
layoutMap: workcaseLayoutMap,
viewLoader,
notFoundComponent: () => Promise.resolve({
default: {
template: '<div style="padding: 20px; text-align: center;"><h2>404 - 页面未找到</h2></div>'
}
})
}
// Workcase 路由生成选项
const routeOptions: GenerateSimpleRoutesOptions = {
asRootChildren: false, // 直接作为根级路由,不是某个布局的子路由
iframePlaceholder: () => import('shared/components').then(m => ({ default: m.IframeView })),
verbose: true // 启用详细日志
}
/**
* 添加动态路由Workcase 特定)
* @param views 视图列表(用作菜单)
*/
export function addDynamicRoutes(views: TbSysViewDTO[]) {
if (!views || views.length === 0) {
console.warn('[Workcase] addDynamicRoutes: 视图列表为空')
return
}
console.log('[Workcase] addDynamicRoutes: 开始添加动态路由,视图数量:', views.length)
console.log('[Workcase] addDynamicRoutes: 路由配置:', routeConfig)
console.log('[Workcase] addDynamicRoutes: 路由选项:', routeOptions)
try {
// 使用 shared 中的通用方法生成路由
const routes = generateSimpleRoutes(views, routeConfig, routeOptions)
// 直接将路由添加到根级别不是作为Root的children
routes.forEach(route => {
console.log('[Workcase] addDynamicRoutes: 添加路由', route.path, '使用布局:', route.component?.name || 'unknown')
router.addRoute(route)
})
} catch (error) {
throw error
}
}
/**
* 从 LocalStorage 获取菜单并生成路由Workcase 特定)
*
* 使用 shared 中的通用 loadViewsFromStorage 方法
* 筛选出 service='workcase' 的视图
*/
export function loadRoutesFromStorage(): boolean {
try {
console.log('[Workcase] loadRoutesFromStorage: 开始加载动态路由')
// 使用 shared 中的通用方法加载视图数据
const allViews = loadViewsFromStorage('loginDomain', 'userViews')
console.log('[Workcase] loadRoutesFromStorage: 加载的所有视图数量:', allViews?.length || 0)
if (allViews) {
// 过滤出 workcase 服务的视图
const workcaseViews = allViews.filter((view: TbSysViewDTO) =>
view.service === 'workcase'
)
console.log('[Workcase] loadRoutesFromStorage: 过滤后的 workcase 视图:', workcaseViews)
if (workcaseViews.length === 0) {
console.warn('[Workcase] loadRoutesFromStorage: 没有找到 workcase 服务的视图')
return false
}
// 使用 Workcase 的 addDynamicRoutes 添加路由
addDynamicRoutes(workcaseViews)
return true
}
console.warn('[Workcase] loadRoutesFromStorage: 未能加载视图数据')
return false
} catch (error) {
console.error('[Workcase] loadRoutesFromStorage: 加载路由失败', error)
return false
}
}

View File

@@ -0,0 +1,94 @@
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
// @ts-ignore
import { TokenManager } from 'shared/api'
// @ts-ignore
import { APP_CONFIG } from 'shared/config'
// @ts-ignore
import { loadRoutesFromStorage } from './dynamicRoute'
// workcase应用的动态路由会根据layout字段自动添加不需要预定义Root布局
const routes: RouteRecordRaw[] = []
const router = createRouter({
history: createWebHistory('/workcase'), // 与nginx保持一致使用/workcase前缀
routes
})
// 标记动态路由是否已加载
let dynamicRoutesLoaded = false
// 路由守卫
router.beforeEach((to, from, next) => {
console.log('[Workcase Router] 路由守卫触发:', {
to: to.path,
from: from.path,
meta: to.meta
})
// 设置页面标题
if (to.meta.title) {
document.title = `${to.meta.title} - 工单管理系统`
}
// 检查是否需要登录
const requiresAuth = to.meta.requiresAuth !== false
const hasToken = TokenManager.hasToken()
console.log('[Workcase Router] 认证检查:', {
requiresAuth,
hasToken,
tokenValue: localStorage.getItem('token')
})
// 其他页面:检查是否需要登录
if (requiresAuth && !hasToken) {
// 需要登录但未登录,重定向到 platform 的登录页
// 重要必须使用完整URL包含origin避免被workcase的路由拦截造成循环
const currentUrl = window.location.href
const origin = window.location.origin
// 构建platform登录页的完整URL
const loginUrl = `${origin}/login?redirect=${encodeURIComponent(currentUrl)}`
console.log('[Workcase Router] 未登录重定向到Platform登录页:', loginUrl)
// 使用完整URL跳转跳出workcase的路由系统
window.location.href = loginUrl
return
}
// 如果已登录且动态路由未加载,先加载动态路由
if (hasToken && !dynamicRoutesLoaded) {
console.log('[Workcase Router] 开始加载动态路由...')
console.log('[Workcase Router] LocalStorage 内容:', {
loginDomain: localStorage.getItem('loginDomain'),
token: localStorage.getItem('token')
})
dynamicRoutesLoaded = true
const loaded = loadRoutesFromStorage?.()
console.log('[Workcase Router] 动态路由加载结果:', loaded)
console.log('[Workcase Router] 当前路径:', to.path)
console.log('[Workcase Router] 所有路由:', router.getRoutes().map(r => r.path))
if (loaded) {
// 动态路由加载成功,重新导航以匹配新添加的路由
console.log('[Workcase Router] 动态路由加载成功,重新导航到:', to.path)
next({ ...to, replace: true })
return
} else {
console.warn('[Workcase Router] 动态路由加载失败')
}
}
console.log('[Workcase Router] 继续正常导航')
next()
})
// 重置动态路由加载状态
export function resetDynamicRoutes() {
dynamicRoutesLoaded = false
}
export default router

View File

@@ -0,0 +1,179 @@
/**
* Shared Module Federation 类型声明
* 用于 TypeScript 识别远程模块
*/
// ========== 组件模块 ==========
declare module 'shared/components' {
export const FileUpload: any
export const DynamicFormItem: any
export const IframeView: any
}
declare module 'shared/components/FileUpload' {
import { DefineComponent } from 'vue'
const FileUpload: DefineComponent<{}, {}, any>
export default FileUpload
}
declare module 'shared/components/DynamicFormItem' {
import { DefineComponent } from 'vue'
const DynamicFormItem: DefineComponent<{}, {}, any>
export default DynamicFormItem
}
declare module 'shared/components/iframe/IframeView.vue' {
import { DefineComponent } from 'vue'
const IframeView: DefineComponent<{}, {}, any>
export default IframeView
}
// ========== API 模块 ==========
declare module 'shared/api' {
export const api: any
export const TokenManager: any
}
declare module 'shared/api/auth' {
export const authAPI: any
}
declare module 'shared/api/file' {
export const fileAPI: any
}
// 保留旧的导出路径(向后兼容)
declare module 'shared/FileUpload' {
import { DefineComponent } from 'vue'
const FileUpload: DefineComponent<{}, {}, any>
export default FileUpload
}
declare module 'shared/DynamicFormItem' {
import { DefineComponent } from 'vue'
const DynamicFormItem: DefineComponent<{}, {}, any>
export default DynamicFormItem
}
declare module 'shared/authAPI' {
export const authAPI: any
}
declare module 'shared/fileAPI' {
export const fileAPI: any
}
declare module 'shared/utils' {
export const initAesEncrypt: any
export const getAesInstance: any
export const formatFileSize: any
export const isImageFile: any
export const getFileTypeIcon: any
export const isValidFileType: any
export const getFilePreviewUrl: any
}
declare module 'shared/types' {
import { RouteRecordRaw } from 'vue-router'
export type LoginParam = any
export type LoginDomain = any
export type SysUserVO = any
export type TbSysFileDTO = any
export type SysConfigVO = any
export type ResultDomain<T = any> = any
// 视图类型(用于路由和菜单)
export interface TbSysViewDTO {
viewId?: string
name?: string
parentId?: string
url?: string
component?: string
iframeUrl?: string
icon?: string
type?: number
service?: string
layout?: string
orderNum?: number
description?: string
children?: TbSysViewDTO[]
}
}
declare module 'shared/utils/route' {
import { RouteRecordRaw } from 'vue-router'
import type { TbSysViewDTO } from 'shared/types'
export interface RouteGeneratorConfig {
layoutMap: Record<string, () => Promise<any>>
viewLoader: (componentPath: string) => (() => Promise<any>) | null
staticRoutes?: RouteRecordRaw[]
notFoundComponent?: () => Promise<any>
}
export interface GenerateSimpleRoutesOptions {
asRootChildren?: boolean
iframePlaceholder?: () => Promise<any>
verbose?: boolean
}
export function generateRoutes(
views: TbSysViewDTO[],
config: RouteGeneratorConfig
): RouteRecordRaw[]
export function generateSimpleRoutes(
views: TbSysViewDTO[],
config: RouteGeneratorConfig,
options?: GenerateSimpleRoutesOptions
): RouteRecordRaw[]
export function buildMenuTree(
views: TbSysViewDTO[],
staticRoutes?: RouteRecordRaw[]
): TbSysViewDTO[]
export function filterMenusByPermissions(
views: TbSysViewDTO[],
permissions: string[]
): TbSysViewDTO[]
export function findMenuByPath(
views: TbSysViewDTO[],
path: string
): TbSysViewDTO | null
export function getMenuPath(
views: TbSysViewDTO[],
targetViewId: string
): TbSysViewDTO[]
export function getFirstAccessibleMenuUrl(
views: TbSysViewDTO[]
): string | null
export function loadViewsFromStorage(
storageKey?: string,
viewsPath?: string
): TbSysViewDTO[] | null
}
declare module 'shared/utils/device' {
export enum DeviceType {
MOBILE = 'mobile',
DESKTOP = 'desktop'
}
export function getDeviceType(): DeviceType
export function isMobile(): boolean
export function isDesktop(): boolean
export function useDevice(): any
}
// ========== Layouts 布局模块 ==========
declare module 'shared/layouts' {
import { DefineComponent } from 'vue'
export const BlankLayout: DefineComponent<{}, {}, any>
}

View File

@@ -0,0 +1,247 @@
.ai-chat-system {
display: flex;
height: 100vh;
background: #f5f7fa;
// 左侧边栏
.chat-sidebar {
width: 200px;
background: #fff;
border-right: 1px solid #e4e7ed;
display: flex;
flex-direction: column;
.sidebar-header {
padding: 20px 16px;
border-bottom: 1px solid #e4e7ed;
h1 {
font-size: 16px;
margin: 0;
color: #303133;
}
}
.nav-section {
padding: 12px 8px;
.nav-item.new-chat {
background: #409eff;
color: #fff;
&:hover {
background: #66b1ff;
}
}
.nav-item {
display: flex;
align-items: center;
gap: 10px;
padding: 10px 12px;
margin-bottom: 2px;
border-radius: 6px;
cursor: pointer;
color: #606266;
transition: all 0.2s;
&:hover {
background: #f5f7fa;
}
&.active {
background: #ecf5ff;
color: #409eff;
}
span {
font-size: 14px;
}
}
}
.sidebar-footer {
margin-top: auto;
padding: 16px;
text-align: center;
font-size: 12px;
color: #c0c4cc;
border-top: 1px solid #e4e7ed;
}
}
// 主内容区
.chat-main {
flex: 1;
display: flex;
flex-direction: column;
overflow: hidden;
background: #f5f7fa;
.chat-header {
padding: 24px 32px;
background: #fff;
border-bottom: 1px solid #e4e7ed;
h1 {
font-size: 24px;
margin: 0 0 8px 0;
color: #303133;
}
.subtitle {
font-size: 14px;
color: #909399;
margin: 0;
}
}
.chat-area {
flex: 1;
background: #fff;
margin: 24px 32px;
border-radius: 8px;
display: flex;
flex-direction: column;
overflow: hidden;
.ai-info {
display: flex;
align-items: center;
gap: 12px;
padding: 16px 20px;
border-bottom: 1px solid #e4e7ed;
.ai-avatar {
width: 48px;
height: 48px;
border-radius: 50%;
background: #f0f2f5;
display: flex;
align-items: center;
justify-content: center;
font-size: 24px;
}
.ai-details {
flex: 1;
}
.ai-name {
font-size: 16px;
font-weight: 600;
color: #303133;
margin-bottom: 4px;
}
.ai-status {
font-size: 12px;
color: #67c23a;
display: flex;
align-items: center;
gap: 6px;
.status-dot {
width: 6px;
height: 6px;
border-radius: 50%;
background: #67c23a;
animation: pulse 2s infinite;
}
}
}
.messages {
flex: 1;
padding: 20px;
overflow-y: auto;
background: #f5f7fa;
.message {
display: flex;
margin-bottom: 16px;
&.user {
justify-content: flex-end;
.message-content {
background: #409eff;
color: #fff;
}
}
.message-content {
max-width: 60%;
padding: 12px 16px;
background: #fff;
border-radius: 8px;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}
.message-text {
line-height: 1.6;
word-wrap: break-word;
}
.message-time {
font-size: 11px;
color: #c0c4cc;
margin-top: 6px;
}
}
}
.quick-actions {
display: flex;
gap: 12px;
padding: 12px 20px;
border-top: 1px solid #e4e7ed;
border-bottom: 1px solid #e4e7ed;
background: #fff;
.quick-btn {
display: flex;
align-items: center;
gap: 6px;
padding: 8px 16px;
background: #f5f7fa;
border: 1px solid #e4e7ed;
border-radius: 16px;
font-size: 13px;
color: #606266;
cursor: pointer;
transition: all 0.2s;
&:hover {
background: #ecf5ff;
border-color: #409eff;
color: #409eff;
}
}
}
.input-area {
display: flex;
align-items: center;
gap: 12px;
padding: 16px 20px;
background: #fff;
.attach-icon {
font-size: 20px;
color: #909399;
cursor: pointer;
}
}
}
}
}
@keyframes pulse {
0%, 100% {
opacity: 1;
}
50% {
opacity: 0.5;
}
}

View File

@@ -0,0 +1,193 @@
<template>
<div class="ai-chat-system">
<!-- 左右布局 -->
<!-- 左侧边栏 -->
<aside class="chat-sidebar">
<!-- 标头 -->
<div class="sidebar-header">
<h1>智能客服系统</h1>
</div>
<!-- 新增对话按钮 -->
<div class="nav-section">
<div class="nav-item new-chat" @click="startNewChat">
<ElIcon><Plus /></ElIcon>
<span>新建对话</span>
</div>
</div>
<!-- 历史对话列表 -->
<ChatHistory
:chatHistory="chatHistory"
:currentChatId="currentChatId"
@loadChat="loadChat"
/>
<div class="sidebar-footer">
v2.1.0 (Build 2025)
</div>
</aside>
<!-- 主内容区 -->
<div class="chat-main">
<!-- header -->
<div class="chat-header">
<h1>泰豪小电-对内</h1>
<p class="subtitle">Real-time Support Agent</p>
</div>
<!-- 聊天区域 -->
<div class="chat-area">
<!-- 智能体信息 助手 -->
<div class="ai-info">
<div class="ai-avatar">🤖</div>
<div class="ai-details">
<div class="ai-name">泰豪智能服务助手</div>
<div class="ai-status">
<span class="status-dot"></span>
基于 RAG 知识库 · 24小时在线
</div>
</div>
</div>
<!-- 聊天记录 -->
<div class="messages" ref="messagesRef">
<div
v-for="msg in messages"
:key="msg.id"
class="message"
:class="msg.role"
>
<div class="message-content">
<div class="message-text">{{ msg.text }}</div>
<div class="message-time">{{ msg.time }}</div>
</div>
</div>
</div>
<!-- footer -->
<!-- 默认提示词 -->
<div class="quick-actions">
<button class="quick-btn" @click="quickReply('设备操作手册')">
<ElIcon><Document /></ElIcon>
设备操作手册
</button>
<button class="quick-btn" @click="quickReply('故障排查指南')">
<ElIcon><Warning /></ElIcon>
故障排查指南
</button>
<button class="quick-btn" @click="quickReply('维保服务规范')">
<ElIcon><List /></ElIcon>
维保服务规范
</button>
<button class="quick-btn" @click="quickReply('技术参数查询')">
<ElIcon><Search /></ElIcon>
技术参数查询
</button>
</div>
<!-- 输入框 -->
<div class="input-area">
<ElIcon class="attach-icon"><Paperclip /></ElIcon>
<ElInput
v-model="inputText"
placeholder="描述您的问题 (如: 发电机启动失败异常)..."
@keyup.enter="sendMessage"
/>
<ElButton type="primary" :icon="Promotion" circle @click="sendMessage" />
</div>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { ElButton, ElInput, ElIcon } from 'element-plus';
import {
Plus,
Document,
Warning,
List,
Search,
Paperclip,
Promotion
} from '@element-plus/icons-vue';
import ChatHistory from './components/ChatHistory.vue';
// 当前选中的对话ID
const currentChatId = ref(1);
// 历史对话列表
const chatHistory = ref([
{ id: 1, title: '发电机故障咨询', time: '今天 10:30' },
{ id: 2, title: '设备维保规范查询', time: '今天 09:15' },
{ id: 3, title: '配件更换流程', time: '昨天 16:42' },
{ id: 4, title: 'TH-500GF参数查询', time: '昨天 14:20' },
{ id: 5, title: '巡检报告模板', time: '12月10日' },
{ id: 6, title: '客户投诉处理流程', time: '12月09日' }
]);
// 聊天消息列表
const messages = ref([
{ id: 1, role: 'assistant', text: '您好,欢迎使用泰豪智能客服,请问有什么可以帮您的?', time: '10:00' }
]);
// 输入框文本
const inputText = ref('');
// 消息容器引用
const messagesRef = ref<HTMLElement | null>(null);
// 开始新对话
const startNewChat = () => {
const newId = Date.now();
chatHistory.value.unshift({
id: newId,
title: '新对话',
time: '刚刚'
});
currentChatId.value = newId;
messages.value = [
{
id: 1,
role: 'assistant',
text: '您好,欢迎使用泰豪智能客服,请问有什么可以帮您的?',
time: new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
}
];
};
// 加载历史对话
const loadChat = (chatId: number) => {
currentChatId.value = chatId;
// 模拟加载历史对话
messages.value = [
{ id: 1, role: 'assistant', text: '您好,欢迎使用泰豪智能客服,请问有什么可以帮您的?', time: '10:00' }
];
};
// 发送消息
const sendMessage = () => {
if (!inputText.value.trim()) return;
messages.value.push({
id: Date.now(),
role: 'user',
text: inputText.value,
time: new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
});
inputText.value = '';
};
// 快捷回复
const quickReply = (text: string) => {
inputText.value = text;
sendMessage();
};
</script>
<style scoped lang="scss">
@import url("./AIChatView.scss");
</style>

View File

@@ -0,0 +1,61 @@
.chat-history {
flex: 1;
overflow-y: auto;
padding: 0 8px;
.history-title {
font-size: 12px;
color: #909399;
padding: 8px 12px;
margin-bottom: 4px;
}
.history-list {
display: flex;
flex-direction: column;
gap: 2px;
}
.history-item {
display: flex;
align-items: center;
gap: 10px;
padding: 10px 12px;
border-radius: 6px;
cursor: pointer;
color: #606266;
transition: all 0.2s;
&:hover {
background: #f5f7fa;
}
&.active {
background: #ecf5ff;
color: #409eff;
}
.el-icon {
font-size: 16px;
flex-shrink: 0;
}
.history-info {
flex: 1;
min-width: 0;
.history-name {
font-size: 14px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.history-time {
font-size: 12px;
color: #909399;
margin-top: 2px;
}
}
}
}

View File

@@ -0,0 +1,51 @@
<template>
<div class="chat-history">
<div class="history-title">历史对话</div>
<div class="history-list">
<div
v-for="chat in chatHistory"
:key="chat.id"
class="history-item"
:class="{ active: currentChatId === chat.id }"
@click="handleLoadChat(chat.id)"
>
<ElIcon><ChatLineRound /></ElIcon>
<div class="history-info">
<div class="history-name">{{ chat.title }}</div>
<div class="history-time">{{ chat.time }}</div>
</div>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { ElIcon } from 'element-plus';
import { ChatLineRound } from '@element-plus/icons-vue';
interface ChatItem {
id: number;
title: string;
time: string;
}
interface Props {
chatHistory: ChatItem[];
currentChatId: number;
}
interface Emits {
(e: 'loadChat', chatId: number): void;
}
defineProps<Props>();
const emit = defineEmits<Emits>();
const handleLoadChat = (chatId: number) => {
emit('loadChat', chatId);
};
</script>
<style scoped lang="scss">
@import url("./ChatHistory.scss");
</style>

View File

@@ -0,0 +1,47 @@
<template>
<div class="login-page">
<div class="login-box">
<h1>工单管理系统</h1>
<p>请先登录主系统</p>
<el-button type="primary" @click="goToMainSystem">
前往主系统登录
</el-button>
</div>
</div>
</template>
<script setup lang="ts">
const goToMainSystem = () => {
window.location.href = 'http://localhost:5002'
}
</script>
<style scoped>
.login-page {
width: 100%;
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}
.login-box {
background: white;
padding: 48px;
border-radius: 12px;
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
text-align: center;
}
.login-box h1 {
margin-bottom: 16px;
font-size: 24px;
color: #333;
}
.login-box p {
margin-bottom: 24px;
color: #666;
}
</style>

View File

@@ -1,13 +1,17 @@
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import { federation } from '@module-federation/vite'
import { resolve, dirname } from 'path'
import { fileURLToPath } from 'url'
const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
export default defineConfig({
export default defineConfig(({ mode }) => ({
// 开发和生产环境都通过nginx代理访问/workcase
base: '/workcase/',
plugins: [
vue({
script: {
@@ -15,7 +19,23 @@ export default defineConfig({
propsDestructure: true
}
}),
vueJsx()
vueJsx(),
federation({
name: 'workcase',
remotes: {
shared: {
type: 'module',
name: 'shared',
entry: 'http://localhost:5000/remoteEntry.js'
}
},
shared: {
vue: {},
'vue-router': {},
'element-plus': {},
axios: {}
}
})
],
define: {
@@ -34,6 +54,7 @@ export default defineConfig({
port: 5003,
host: true,
cors: true,
open: '/workcase/', // 开发时自动打开到 /workcase/ 路径
proxy: {
'/api': {
target: 'http://localhost:8180',
@@ -60,4 +81,4 @@ export default defineConfig({
}
}
}
})
}))