<template>
<el-breadcrumb separator="/">
<!-- 始终添加首页作为第一个面包屑项 -->
<el-breadcrumb-item :to="homePath" v-if="showHome">
Home
</el-breadcrumb-item>
<!-- 动态生成其他层级的面包屑 -->
<el-breadcrumb-item
v-for="(item, index) in dynamicBreadcrumbs"
:key="index"
:to="isLastItem(index) ? '' : item.path"
>
{{ item.title }}
</el-breadcrumb-item>
</el-breadcrumb>
</template>
<script setup>
import { useRoute } from 'vue-router'
import { computed, ref, onMounted } from 'vue'
const route = useRoute()
// 配置首页路径(根据你的实际首页路径调整)
const homePath = '/'
// 是否显示首页(除了首页本身)
const showHome = computed(() => route.path !== homePath)
// 解析路由路径生成面包屑层级
const dynamicBreadcrumbs = computed(() => {
// 分割路径为片段(去除空字符串和首页)
const pathSegments = route.path.split('/').filter(segment => segment)
// 构建完整路径数组
const fullPaths = []
pathSegments.forEach((segment, index) => {
const fullPath = '/' + pathSegments.slice(0, index + 1).join('/')
fullPaths.push({
path: fullPath,
segment: segment
})
})
// 为每个路径片段匹配对应的标题
return fullPaths.map(item => {
// 尝试从路由元信息中获取标题
const matchedRecord = route.matched.find(r => r.path === item.path)
if (matchedRecord && matchedRecord.meta.title) {
return {
path: item.path,
title: matchedRecord.meta.title
}
}
// 如果没有元信息,使用路径片段的友好名称
return {
path: item.path,
title: formatSegmentToTitle(item.segment)
}
})
})
// 判断是否为最后一项
const isLastItem = (index) => {
return index === dynamicBreadcrumbs.value.length - 1
}
// 将路径片段格式化为友好标题
const formatSegmentToTitle = (segment) => {
// 处理动态路由参数(如 _id 或 :id)
if (segment.startsWith('_') || segment.includes(':')) {
return '详情'
}
// 首字母大写,其他情况可以根据需要调整
return segment.charAt(0).toUpperCase() + segment.slice(1)
}
// 调试信息,帮助排查问题
// onMounted(() => {
// console.log('当前路由路径:', route.path)
// console.log('路由匹配记录:', route.matched)
// console.log('生成的面包屑:', dynamicBreadcrumbs.value)
// })
</script>
<style scoped>
::v-deep .el-breadcrumb__item:last-child .el-breadcrumb__inner {
color: #666;
cursor: default;
font-weight: normal;
}
</style>