<template>
  <el-breadcrumb class="app-breadcrumb" separator=">">
    <transition-group name="breadcrumb">
      <el-breadcrumb-item v-for="(item,index)  in levelList" :key="item.path" v-if="item.meta.title">
        <span v-if="item.redirect==='noredirect'||index==levelList.length-1" class="no-redirect">{{item.meta.title}}</span>
        <router-link v-else :to="item.redirect">{{item.meta.title}}</router-link>
      </el-breadcrumb-item>
    </transition-group>
  </el-breadcrumb>
</template>

<script>
import { mapGetters } from 'vuex';

export default {
  created() {
    this.getBreadcrumb();
  },
  data() {
    return {
      levelList: null,
    };
  },
  watch: {
    $route() {
      this.getBreadcrumb();
    },
  },
  computed: {
    ...mapGetters([
      'currentPath',
    ]),
  },
  methods: {
    getBreadcrumb() {
      const matched = this.$route.matched.filter(item => item.name);
      this.levelList = matched;
      let tmp = {};
      let level = {};
      // 一级 二级菜单
      switch (this.levelList.length) {
        case 2:
          if (this.levelList[1].meta.parent) {
            level = {
              meta: {
                title: this.levelList[1].meta.parent,
              },
              path: `no-exists-${this.currentPath}`,
              redirect: this.currentPath,
            };
            tmp = this.levelList[1];
            this.levelList[1] = level;
            this.levelList.push(tmp);
          }
          break;
        case 3:
          if (this.levelList[2].meta.parent) {
            level = {
              meta: {
                title: this.levelList[2].meta.parent,
              },
              path: `no-exists-${this.currentPath}`,
              redirect: this.currentPath,
            };
            tmp = this.levelList[2];
            this.levelList[2] = level;
            this.levelList.push(tmp);
          }
          break;
        default:
      }
      // }
    },
  },
  mounted() {
    this.getBreadcrumb();
  },
};
</script>

<style rel="stylesheet/less" lang="less">
  .app-breadcrumb.el-breadcrumb {
    display: inline-block;
    font-size: 14px;
    line-height: 50px;
    margin-left: 20px;
    .no-redirect {
      color: #606266;
      cursor: text;
    }
  }
  .app-breadcrumb .el-breadcrumb__inner a {
    font-weight: normal !important;
  }
</style>
