nuxt项目中实现面包屑导航

<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>
      

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值