2级sidebar

This commit is contained in:
2025-12-13 15:56:12 +08:00
parent 3442f96214
commit b57a002de8
46 changed files with 1529 additions and 203 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

View File

@@ -0,0 +1,262 @@
.sidebar-layout {
display: flex;
width: 100%;
height: 100vh;
overflow: hidden;
}
// ==================== 侧边栏(内层子导航样式)====================
.sidebar {
width: 180px;
height: 100%;
background: #fff;
display: flex;
flex-direction: column;
color: #333;
flex-shrink: 0;
transition: width 0.3s ease;
border-right: 1px solid #e4e7ed;
&.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 #e4e7ed;
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: #909399;
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: 36px;
height: 36px;
border-radius: 6px;
object-fit: contain;
}
.logo-text {
font-size: 16px;
font-weight: 600;
color: #303133;
}
}
// 导航菜单
.nav-menu {
flex: 1;
overflow-y: auto;
padding: 16px 0;
&::-webkit-scrollbar {
width: 4px;
}
&::-webkit-scrollbar-thumb {
background: rgba(0, 0, 0, 0.15);
border-radius: 4px;
}
}
.nav-section {
padding: 0;
}
.nav-item {
display: flex;
align-items: center;
gap: 10px;
padding: 10px 20px;
margin-bottom: 0;
cursor: pointer;
transition: all 0.2s ease;
color: #606266;
font-size: 14px;
&:hover {
background: rgba(124, 58, 237, 0.1);
color: #7c3aed;
}
&.active {
background: rgba(124, 58, 237, 0.15);
color: #7c3aed;
border-right: 3px solid #7c3aed;
}
.el-icon {
font-size: 16px;
flex-shrink: 0;
}
span {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
}
// 用户信息
.user-section {
padding: 16px 20px;
border-top: 1px solid #e4e7ed;
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: #303133;
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: 180px;
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,368 @@
<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">
<template v-for="item in menuItems" :key="item.key">
<!-- 父菜单 -->
<div
class="nav-item"
:class="{ active: activeMenu === item.key, 'has-children': item.children }"
@click="item.children ? toggleMenu(item) : handleMenuClick(item)"
>
<el-icon><component :is="item.icon" /></el-icon>
<span v-if="!collapsed">{{ item.label }}</span>
<!-- 展开/折叠图标 -->
<el-icon v-if="item.children && !collapsed" class="expand-icon">
<ArrowDown v-if="item.expanded" />
<ArrowRight v-else />
</el-icon>
</div>
<!-- 子菜单 -->
<template v-if="item.children && item.expanded && !collapsed">
<div
v-for="child in item.children"
:key="child.key"
class="nav-item nav-child-item"
:class="{ active: activeMenu === child.key }"
@click="handleMenuClick(child)"
>
<el-icon><component :is="child.icon" /></el-icon>
<span>{{ child.label }}</span>
</div>
</template>
</template>
</div>
</nav>
</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,
ArrowDown,
ArrowRight
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
interface Props {
service?: string // 服务名称platform, bidding, workcase
}
interface MenuItem {
key: string
label: string
icon: string
url?: string
type: 'route' | 'iframe'
children?: MenuItem[] // 子菜单
expanded?: boolean // 是否展开
}
const props = withDefaults(defineProps<Props>(), {
service: undefined // 不设默认值,从路由自动检测
})
const router = useRouter()
const route = useRoute()
// 自动检测当前服务
const currentService = computed(() => {
// 优先使用 props
if (props.service) {
return props.service
}
// 从 route.meta 获取
const meta = route.meta as any
if (meta?.service) {
return meta.service
}
// 从 URL 路径推断服务(最可靠的方式)
const hostname = window.location.hostname
const pathname = window.location.pathname
// 根据 URL 路径判断服务
// localhost/workcase/... -> workcase
// localhost/platform/... -> platform
// localhost/bidding/... -> bidding
if (pathname.includes('/workcase/')) {
return 'workcase'
}
if (pathname.includes('/platform/')) {
return 'platform'
}
if (pathname.includes('/bidding/')) {
return 'bidding'
}
// 从 localStorage 的 loginDomain 中推断(基于当前路由匹配的视图)
try {
const loginDomainStr = localStorage.getItem('loginDomain')
if (loginDomainStr) {
const loginDomain = JSON.parse(loginDomainStr)
const userViews = loginDomain.userViews || []
// 找到当前路由对应的视图
const currentView = userViews.find((v: any) =>
v.layout === 'AdminSidebarLayout' &&
v.url === route.path
)
if (currentView?.service) {
return currentView.service
}
// 如果没找到精确匹配,尝试前缀匹配
const matchedView = userViews.find((v: any) =>
v.layout === 'AdminSidebarLayout' &&
route.path.startsWith(v.url)
)
if (matchedView?.service) {
return matchedView.service
}
}
} catch (error) {
console.error('自动检测服务失败:', error)
}
// 默认返回 workcase
return 'workcase'
})
// 状态管理
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 || []
const service = currentService.value
console.log(`📋 [${service}] 加载用户视图:`, userViews)
// 过滤出 AdminSidebarLayout 的菜单(使用当前服务动态过滤)
const allSidebarViews = userViews.filter((view: any) =>
view.layout === 'AdminSidebarLayout' &&
(view.type === 0 || view.type === 1) && // type 0=目录 1=菜单
view.service === service && // 动态匹配服务
view.url?.startsWith('/admin') // 只留 admin 路由
)
// 分离顶级菜单和子菜单
const topLevelViews = allSidebarViews.filter((view: any) => !view.parentId)
const childViews = allSidebarViews.filter((view: any) => view.parentId)
console.log(`🔍 [${service}] 顶级视图:`, topLevelViews)
console.log(`🔍 [${service}] 子视图:`, childViews)
// 按 orderNum 排序
topLevelViews.sort((a: any, b: any) => (a.orderNum || 0) - (b.orderNum || 0))
// 转换为 MenuItem 格式并构建树形结构
const menuItems: MenuItem[] = topLevelViews.map((view: any) => {
const isIframe = view.viewType === 'iframe' || !!view.iframeUrl
let menuUrl = view.url
if (isIframe && view.url && (view.url.startsWith('http://') || view.url.startsWith('https://'))) {
menuUrl = `/${view.viewId}`
}
// 查找子菜单
const children = childViews
.filter((child: any) => child.parentId === view.viewId)
.sort((a: any, b: any) => (a.orderNum || 0) - (b.orderNum || 0))
.map((child: any) => ({
key: child.viewId || child.name,
label: child.name,
icon: child.icon || 'Document',
url: child.url,
type: (child.viewType === 'iframe' || !!child.iframeUrl) ? 'iframe' : 'route' as 'iframe' | 'route'
}))
return {
key: view.viewId || view.name,
label: view.name,
icon: view.icon || 'Grid',
url: menuUrl,
type: isIframe ? 'iframe' : 'route',
children: children.length > 0 ? children : undefined,
expanded: false // 默认折叠
}
})
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 toggleMenu = (item: MenuItem) => {
if (item.children) {
item.expanded = !item.expanded
}
}
// 处理菜单点击
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
}
}
// 监听服务变化,重新加载菜单
watch(
currentService,
() => {
console.log(`🔄 服务切换到: ${currentService.value},重新加载菜单`)
menuItems.value = loadMenuFromStorage()
}
)
// 监听路由变化,同步激活菜单
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("./AdminSidebarLayout.scss");
</style>

View File

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

View File

@@ -14,9 +14,10 @@ type SysMenu = TbSysViewDTO
// 视图类型常量(对应后端的 type 字段)
const ViewType = {
MENU: 1, // 菜单
PAGE: 2, // 页面
BUTTON: 3 // 按钮
NAVBAR: 0, // 导航栏
SIDEBAR: 1, // 侧边栏
BUTTON: 2, // 按钮
ROUTE: 3 // 空白页(路由页面)
} as const
/**
@@ -74,33 +75,33 @@ export function generateRoutes(
if (route) {
routes.push(route)
// 递归提取所有 PAGE 类型的子菜单
// 递归提取所有 ROUTE 类型的子菜单
extractPageChildren(route, pageRoutes, config)
}
})
// 将 PAGE 类型的路由添加到路由列表
// 将 ROUTE 类型的路由添加到路由列表
routes.push(...pageRoutes)
return routes
}
/**
* 递归提取路由中的 PAGE 类型子菜单
* 递归提取路由中的 ROUTE 类型子菜单
*/
function extractPageChildren(
route: any,
pageRoutes: RouteRecordRaw[],
config: RouteGeneratorConfig
) {
// 检查当前路由是否有 PAGE 类型的子菜单
// 检查当前路由是否有 ROUTE 类型的子菜单
if (route.meta?.pageChildren && Array.isArray(route.meta.pageChildren)) {
route.meta.pageChildren.forEach((pageMenu: SysMenu) => {
const pageRoute = generateRouteFromMenu(pageMenu, config, true)
if (pageRoute) {
pageRoutes.push(pageRoute)
} else {
console.error(`[路由生成] 生成独立PAGE路由失败: ${pageMenu.name}`)
console.error(`[路由生成] 生成独立ROUTE路由失败: ${pageMenu.name}`)
}
})
// 清理临时数据
@@ -171,7 +172,7 @@ function generateRouteFromMenu(
route.component = config.layoutMap[menu.component]
} else if (hasChildren && isTopLevel) {
// 如果有子菜单但没有指定布局,根据菜单类型选择默认布局
if (menu.type === ViewType.MENU && !menu.parentId) {
if (menu.type === ViewType.SIDEBAR && !menu.parentId) {
route.component = config.layoutMap['SidebarLayout']
} else {
route.component = config.layoutMap['BasicLayout']
@@ -220,7 +221,7 @@ function generateRouteFromMenu(
const normalChildren: SysMenu[] = []
menu.children!.forEach((child: SysMenu) => {
if (child.type === ViewType.PAGE) {
if (child.type === ViewType.ROUTE) {
pageChildren.push(child)
} else {
normalChildren.push(child)
@@ -235,7 +236,7 @@ function generateRouteFromMenu(
}
})
// PAGE 类型的菜单保存到 meta
// ROUTE 类型的菜单保存到 meta
if (pageChildren.length > 0) {
route.meta.pageChildren = pageChildren
}
@@ -244,12 +245,12 @@ function generateRouteFromMenu(
// 处理有子菜单的情况
route.children = []
// 分离 PAGE 类型的子菜单和普通子菜单
// 分离 ROUTE 类型的子菜单和普通子菜单
const pageChildren: SysMenu[] = []
const normalChildren: SysMenu[] = []
menu.children!.forEach((child: SysMenu) => {
if (child.type === ViewType.PAGE) {
if (child.type === ViewType.ROUTE) {
pageChildren.push(child)
} else {
normalChildren.push(child)