<template>
  <div id="breadcrumb">
    <el-tag v-for="(item, index) in list" :key="index" type="primary" size="small" closable class="tags" @close="closeTag(index)">{{ item.name }}</el-tag>
  </div>
</template>

<script>
export default {
  name: 'breadcrumb',
  props: {},
  components: {},
  data: () => ({
    list: [],
  }),
  created() {
    this.getList();
  },
  computed: {},
  methods: {
    getList() {
      console.log('bread getlist');
      //将面包屑列表存到sessionStorage中,存为list,{name:xxx,path:xxx}形式
      //1)是从sessionStorage中取出之前的列表
      let o_list = sessionStorage.getItem('bread');
      if (o_list !== null) {
        //如果之前有浏览记录,那就将值取出来
        this.$set(this, `list`, JSON.parse(o_list));
      }
      //2)查询当前路由是否已经存在
      let { name, path } = this.$route;
      if (path === '/admin' || path === '/admin/index') return;
      let object = { name: name, path: path };
      let res = [];
      //列表有值,过滤看看有没有当前路由
      if (this.list.length > 0) {
        res = this.list.filter(fil => fil.path === object.path);
        if (res.length <= 0) {
          //没有当前路由,加上
          this.list.push(object);
          sessionStorage.setItem(`bread`, JSON.stringify(this.list));
        }
      } else {
        //列表没有值,直接加上
        this.list.push(object);
        sessionStorage.setItem(`bread`, JSON.stringify(this.list));
      }
    },
    closeTag(index) {
      let elseList = this.list.filter((fil, filIndex) => filIndex !== index);
      this.$set(this, `list`, elseList);
      sessionStorage.setItem('bread', JSON.stringify(elseList));
      if (this.list.length > 0) this.$router.push(this.list[this.list.length - 1].path);
      else this.$router.push({ path: '/admin/index' });
    },
  },
};
</script>

<style lang="less" scoped>
.tags {
  margin: 0 0.3rem;
}
</style>
