Files
KCGL/inventory-web/src/layout/components/Sidebar/index.vue

95 lines
2.5 KiB
Vue

<template>
<el-menu
:default-active="activeMenu"
background-color="#304156"
text-color="#bfcbd9"
active-text-color="#409EFF"
:unique-opened="true"
router
class="el-menu-vertical"
>
<template v-for="route in menuRoutes" :key="route.path">
<el-menu-item
v-if="!route.children || route.children.length === 1"
:index="resolvePath(route)"
>
<el-icon v-if="getMeta(route).icon">
<component :is="getMeta(route).icon" />
</el-icon>
<span>{{ getMeta(route).title }}</span>
</el-menu-item>
<el-sub-menu v-else :index="route.path">
<template #title>
<el-icon v-if="route.meta && route.meta.icon">
<component :is="route.meta.icon" />
</el-icon>
<span>{{ route.meta?.title }}</span>
</template>
<el-menu-item
v-for="child in route.children"
:key="child.path"
:index="resolvePath(route, child)"
>
<template #title>
<span>{{ child.meta?.title }}</span>
</template>
</el-menu-item>
</el-sub-menu>
</template>
</el-menu>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
const route = useRoute()
const router = useRouter()
// 1. 获取当前激活的菜单路径
const activeMenu = computed(() => {
return route.path
})
// 2. 获取需要在菜单中显示的路由(过滤掉 hidden 的路由)
const menuRoutes = computed(() => {
return router.options.routes.filter((r: any) => !r.meta?.hidden)
})
// 3. 辅助函数:获取 meta 信息
const getMeta = (route: any) => {
if (route.meta) return route.meta
// 如果是 layout 嵌套层(如首页),取第一个子路由的 meta
if (route.children && route.children.length > 0) {
return route.children[0].meta
}
return {}
}
// 4. 辅助函数:拼接路径
const resolvePath = (parent: any, child?: any) => {
// 如果是首页这种 layout 嵌套结构
if (!child && parent.children && parent.children.length === 1) {
return parent.path === '/' ? '/dashboard' : parent.path + '/' + parent.children[0].path
}
// 如果是普通子菜单
if (child) {
return parent.path + '/' + child.path
}
return parent.path
}
</script>
<style scoped>
.el-menu-vertical {
border-right: none; /* 去掉 Element Plus 菜单默认的右边框 */
width: 100%;
}
:deep(.el-menu-item.is-active) {
background-color: #263445 !important;
}
</style>