陶杰
2024-08-22 973662aeae3e7c788c14671d17c5962395141770
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
<template>
  <el-breadcrumb class="el-ext-breadcrumb" v-bind="$attrs">
    <el-breadcrumb-item v-for="(item, index) in levelList" :key="index">
      <span v-if="index == levelList.length - 1">{{ item.title }}</span>
      <a v-else @click.prevent="handleLink(item)">{{ item.title }}</a>
    </el-breadcrumb-item>
  </el-breadcrumb>
</template>
 
<script>
const { compile } = require('path-to-regexp')
 
export default {
  name: 'ElExtBreadcrumb',
  props: {
    menus: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      levelList: [],
    }
  },
  watch: {
    $route() {
      this.getBreadcrumb()
    },
  },
  mounted() {
    this.getBreadcrumb()
  },
  methods: {
    getBreadcrumb() {
      const timer = setTimeout(() => {
        const levelList = []
        const { params } = this.$route
        this.$route.matched.forEach((route) => {
          if (
            route.instances.default &&
            route.instances.default.$metaInfo &&
            route.instances.default.$metaInfo.title
          ) {
            const toPath = compile(route.path)
            levelList.push({
              title: route.instances.default.$metaInfo.title,
              path: toPath(params),
            })
          }
        })
        this.levelList = levelList
        clearTimeout(timer)
      }, 100)
    },
    handleLink(item) {
      const mPath = item.path
      const firstChild = this.findFirstChild(mPath, this.menus)
      this.$router.push(firstChild)
    },
    findFirstChild(mPath, routes) {
      let firstChild = mPath
      if (!routes) {
        return firstChild
      }
      for (const route of routes) {
        if (route.fullPath === mPath) {
          if (route.children && route.children.length > 0) {
            return this.getLeafChild(route.children)
          } else {
            return mPath
          }
        } else if (route.children && route.children.length > 0) {
          firstChild = this.findFirstChild(mPath, route.children)
        }
      }
      return firstChild
    },
    getLeafChild(array) {
      const first = array[0]
      if (first.children && first.children.length > 0) {
        return this.getLeafChild(first.children)
      } else {
        return first.fullPath
      }
    },
  },
}
</script>
 
<style scoped lang="scss"></style>