vue项目Tag导航

实现 tap 点击跳转

点击删除跳转条件

  1. 删除的不是自身:不用跳转
  2. 删除的是最后一个:跳转到最后一个
  3. 删除的是自身且不是最后一个:跳转到后一个(相当于当前元素下标)
<template>
  <div class="tag">
    <el-tag
      size="small"
      v-for="(item, index) in tags"
      :key="index"
      :effect="$route.name == item.name ? 'dark' : 'plain'"
      :closable="item.name !== 'home'"
      style="cursor: pointer"
      @click="changeMenu(item)"
      @close="handleClose(item, index)"
      >{{ item.label }}</el-tag
    >
  </div>
</template>

<script>
import { mapMutations, mapState } from "vuex";

export default {
  computed: {
    // 从vuex获取的数据
    ...mapState({ tags: (state) => state.top.tabsList }),
  },
  methods: {
    // 触发vuex的mutations删除方法
    ...mapMutations(["closeTag"]),
    // 点击
    changeMenu(item) {
      this.$router.push(item.path);
    },
    // tag删除
    handleClose(item, index) {
      // item:tag元素,index:tag 索引
      this.closeTag(item);
      let length = this.tags.length;
      // 1、删除的不是自己,不用跳转
      if (this.$route.name !== item.name) {
        return;
      }
      // 2、删除最后一个,跳转到最后一个
      if (index == length) {
        this.$router.push(this.tags[index - 1].path);
      } else {
        // 3、删除的是自己,跳转到下一个
        this.$router.push(this.tags[index].path);
      }
    },
  },
};
</script>

<style lang="less" scoped>
.tag {
  margin-bottom: 20px;
  .el-tag {
    margin-right: 10px;
  }
}
</style>