Breadcrumb.vue 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <!-- src/components/Breadcrumb.vue -->
  2. <template>
  3. <el-breadcrumb separator="/" class="app-breadcrumb">
  4. <el-breadcrumb-item :to="{ path: '/' }">{{ $t('common.home') }}</el-breadcrumb-item>
  5. <el-breadcrumb-item
  6. v-for="item in breadcrumbItems"
  7. :key="item.path"
  8. :to="item.path === $route.path ? undefined : { path: item.path }"
  9. >
  10. {{ item.name }}
  11. </el-breadcrumb-item>
  12. </el-breadcrumb>
  13. </template>
  14. <script setup>
  15. import { computed } from 'vue'
  16. import { useRoute } from 'vue-router'
  17. import { useI18n } from 'vue-i18n'
  18. const { t } = useI18n() // 获取t函数// 导入useI18n
  19. const route = useRoute()
  20. const breadcrumbItems = computed(() => {
  21. const items = []
  22. const processedPaths = new Set() // 用于跟踪已处理的路径
  23. console.log(2222, route)
  24. // 获取匹配的路由记录
  25. const matchedRoutes = route.matched.filter(item => item.meta && item.meta.title)
  26. // 遍历匹配的路由,生成面包屑项
  27. matchedRoutes.forEach((matchedRoute) => {
  28. // 跳过首页 '/'
  29. if (matchedRoute.path === '/') return
  30. // 获取路由标题
  31. // 使用 $t() 函数翻译标题
  32. const title = t(matchedRoute.meta.title)
  33. // 构造完整路径
  34. let path = matchedRoute.path
  35. // 如果路径中有参数,需要替换参数
  36. if (route.params) {
  37. Object.keys(route.params).forEach(param => {
  38. path = path.replace(`:${param}`, route.params[param])
  39. })
  40. }
  41. //如果路径中有query参数,需要添加到路径中
  42. if (route.query) {
  43. const queryParams = new URLSearchParams(route.query)
  44. path += '?' + queryParams.toString()
  45. }
  46. // 避免重复添加相同路径的项目
  47. if (!processedPaths.has(path)) {
  48. items.push({
  49. name: title,
  50. path: path
  51. })
  52. processedPaths.add(path)
  53. }
  54. })
  55. return items
  56. })
  57. </script>
  58. <style scoped>
  59. .app-breadcrumb {
  60. padding: 10px 0;
  61. }
  62. </style>