<template>
  <div class="sub-menu">
    <router-link
      tag="button"
      :class="{ btn: true, 'btn-active': isVisit(item.path) }"
      v-for="(item, index) in menuStack"
      :key="item.path"
      :to="item.path"
    >
      {{ item.title }}
      <Icon
        @click="closeMenu(index)"
        :name="isVisit(item.path) ? 'ssiclose_active' : 'ssiclose'"
        :size="16"
      />
    </router-link>
    <slot name="tips" />
  </div>
</template>

<script>
import { mapState } from "vuex";
export default {
  computed: {
    ...mapState({
      menuStack: (state) => state.common.menuStack,
    }),
  },
  methods: {
    isVisit(val) {
      const path = this.$route.path;
      return path === val;
    },
    closeMenu(index) {
      const menuStack = JSON.parse(JSON.stringify(this.menuStack));
      const isVisit = this.isVisit(menuStack[index].path);
      menuStack.splice(index, 1);
      this.$store.commit("common/setMenuStack", menuStack);
      if (isVisit) {
        // 关闭的是当前正在查看的
        const i = Math.max(0, index - 1);
        this.$router.push(menuStack[i].path || "/");
      }
    },
  },
};
</script>

<style lang="less" scoped>
.sub-menu {
  width: 100%;
  overflow-x: auto;
  white-space: nowrap;
  .mg-b(16);
  .btn {
    .fs(14);
    .lh(20);
    .pa(8, 13, 8, 13);
    .mg-r(40);
    color: #252631;
    font-weight: bold;
    border: none;
    background-color: #fff;
    border-radius: 5px;
    cursor: pointer;
  }
  .btn-active {
    color: #fff;
    background-color: #2b63ff;
  }
}
</style>
