index.vue 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <template>
  2. <el-breadcrumb class="app-breadcrumb" separator="/">
  3. <transition-group name="breadcrumb">
  4. <el-breadcrumb-item v-for="(item, index) in levelList" :key="item.path">
  5. <span v-if="item.redirect === 'noRedirect' || index == levelList.length - 1" class="no-redirect">{{
  6. item.meta.title
  7. }}</span>
  8. <a v-else @click.prevent="handleLink(item)">{{ item.meta.title }}</a>
  9. </el-breadcrumb-item>
  10. </transition-group>
  11. </el-breadcrumb>
  12. </template>
  13. <script>
  14. import pathToRegexp from 'path-to-regexp'
  15. export default {
  16. data() {
  17. return {
  18. levelList: null
  19. }
  20. },
  21. watch: {
  22. $route() {
  23. this.getBreadcrumb()
  24. }
  25. },
  26. created() {
  27. this.getBreadcrumb()
  28. },
  29. methods: {
  30. getBreadcrumb() {
  31. // only show routes with meta.title
  32. let matched = this.$route.matched.filter(item => item.meta && item.meta.title)
  33. const first = matched[0]
  34. if (!this.isDashboard(first)) {
  35. matched = [{ path: '/dashboard', meta: { title: '首页' } }].concat(matched)
  36. }
  37. if (matched.length > 1) {
  38. const insertPosition = matched.length - 1
  39. let parent = matched[insertPosition].meta.parent
  40. while (parent) {
  41. const route = this.$router.resolve(parent).route
  42. matched.splice(insertPosition, 0, route)
  43. parent = route.meta.parent
  44. }
  45. }
  46. this.levelList = matched.filter(item => item.meta && item.meta.title && item.meta.breadcrumb !== false)
  47. },
  48. isDashboard(route) {
  49. const name = route && route.name
  50. if (!name) {
  51. return false
  52. }
  53. return name.trim().toLocaleLowerCase() === 'Dashboard'.toLocaleLowerCase()
  54. },
  55. pathCompile(path) {
  56. // To solve this problem https://github.com/PanJiaChen/vue-element-admin/issues/561
  57. const { params } = this.$route
  58. var toPath = pathToRegexp.compile(path)
  59. return toPath(params)
  60. },
  61. handleLink(item) {
  62. const { redirect, path } = item
  63. if (redirect) {
  64. this.$router.push(redirect)
  65. return
  66. }
  67. this.$router.push(this.pathCompile(path))
  68. }
  69. }
  70. }
  71. </script>
  72. <style lang="scss" scoped>
  73. .app-breadcrumb.el-breadcrumb {
  74. display: inline-block;
  75. font-size: 14px;
  76. line-height: 50px;
  77. margin-left: 8px;
  78. .no-redirect {
  79. color: #97a8be;
  80. cursor: text;
  81. }
  82. }
  83. </style>