自定义无路由跳转【面包屑】,超出十个中间显示省略号

面包屑.png

<template>
  <div class="breadcrumb">
    <span v-for="(item, index) in displayedItems" :key="index">
      <span
        class="breadcrumb-item"
        :class="{ 'last-item': index === displayedItems.length - 1 }"
        @click="handleClick(index)"
      >
        {{ item.name }}
      </span>
      <span class="separator" v-if="index < displayedItems.length - 1">/</span>
    </span>
  </div>
</template>

<script>
export default {
  name: "Breadcrumb",
  data() {
    return {
      items: [
        { name: "首页1", link: "#" },
        { name: "仓库信息2", link: "#/warehouse" },
        { name: "设备信息3", link: "#/equipment" },
        { name: "首页4", link: "#" },
        { name: "仓库信息5", link: "#/warehouse" },
        { name: "设备信息6", link: "#/equipment" },
        { name: "首页7", link: "#" },
        { name: "仓库信息8", link: "#/warehouse" },
        { name: "设备信息9", link: "#/equipment" },
        { name: "首页10", link: "#" },
        { name: "仓库信息11", link: "#/warehouse" },
        { name: "设备信息12", link: "#/equipment" },
        { name: "首页13", link: "#" },
        { name: "仓库信息14", link: "#/warehouse" },
        { name: "设备信息15", link: "#/equipment" },
        { name: "首页16", link: "#" }
      ],
      maxDisplayedItems: 10,
    };
  },
  computed: {
    displayedItems() {
      if (this.items.length <= this.maxDisplayedItems) {
        return this.items;
      } else {
        const start = this.items.length - this.maxDisplayedItems + 3; // +2 是因为要保留首页和省略号
        return [
          this.items[0],
          this.items[1],
          { name: "...", link: "" },
          ...this.items.slice(start),
        ];
      }
    },
  },
  methods: {
    // handleClick(index) {
    //   this.items.splice(index + 1, this.items.length - index - 1);
    // },
    handleClick(index) {
      if (this.items.length > this.maxDisplayedItems && index === 2) {
        // 点击的是省略号,不执行任何操作
        return;
      }

      if (this.items.length > this.maxDisplayedItems && index > 2) {
        // 如果点击的是省略号后面的项,需要根据省略的数量调整索引
        const omittedItemsCount = this.items.length - this.maxDisplayedItems
        index = index + omittedItemsCount
      }

      this.items.splice(index + 1, this.items.length - index - 1);
    },
  },
};
</script>

<style scoped>
.breadcrumb {
  display: flex;
  align-items: center;
  font-size: 16px;
}

.breadcrumb-item {
  text-decoration: none;
  color: #333; /* 默认颜色 */
  cursor: pointer;
}

.breadcrumb-item:hover {
  color: #007bff; /* 鼠标悬停时的颜色 */
}
.breadcrumb-item.last-item {
  color: #007bff; /* 最后一个item的颜色 */
  font-weight: bold; /* 加粗字体 */
}

.separator {
  margin: 0 5px; /* 左右间距 */
}
</style>
发表评论 / Comment

用心评论~