<template>
  <el-aside width="210px">
    <div class="menu-header">
      <span>组件库</span>
    </div>
    <el-menu
      ref="elMenu"
      default-active="basic"
      class="menu-vertical"
      :collapse="false"
      :router="true"
      @select="handleSelect"
    >
      <el-menu-item v-for="menu in menus" :key="menu.index" :index="menu.index">
        <i :class="menu.icon"></i>
        <span slot="title">{{menu.label}}</span>
      </el-menu-item>
    </el-menu>
  </el-aside>
</template>

<script>
import menu from "@/api/menu.js";

export default {
  data() {
    return {
      menus: []
    };
  },
  created() {
    this.$router.afterEach(_ => {
      this.syncUrlToMenu();
    });
  },
  mounted() {
    // 加载菜单数据
    menu.getMenus(menus => {
      this.menus = menus;
      this.syncUrlToMenu();
    });
  },
  methods: {
    // 同步当前url地址到目录菜单中，选中对应的目录菜单
    syncUrlToMenu: function() {
      let routePath = this.$route.path;
      if (routePath) {
        routePath = routePath.replace("/", "");
        this.$refs.elMenu.activeIndex = routePath;
        this.handleSelect(routePath);
      }
    },
    handleSelect: function(index) {
      menu.getMenuByIndex(index, m => {
        m && this.$emit("menuChange", m.label);
      });
    }
  }
};
</script>


<style lang="scss" scoped>
.el-aside {
  margin-top: 3px;
  overflow: hidden;
}

.menu-header {
  height: 37px;
  padding-left: 30px;
  border-bottom: 1px solid #EBEEF5;
}

.menu-header span {
  font-size: 14px;
  font-weight: bold;
  line-height: 38px;
  color: #373d41;
}

.menu-vertical:not(.el-menu--collapse) {
  width: 200px;
  height: calc(100% - 39px);
  background: #F5F5F5;
  overflow-x: hidden;
  overflow-y: auto;
}

.el-menu-item {
  height: 45px;
  line-height: 45px;
}

.el-menu-item.is-active {
  background: #FFFFFF;
  margin-right: -1px;
}
</style>
