You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在vue-search-select的MultiListSelect中实现+N More显示

解决vue-search-select MultiListSelect选中项框外显示及添加"+N More"提示的问题

问题分析

你当前的自定义模板是在组件外部额外添加了选中项显示区域,所以选中项会出现在选择框外。需要隐藏组件默认的选中项展示,同时将自定义的"+N More"提示嵌入到选择框内部。

实现方案

1. 完整组件代码

<template>
  <div class="custom-multi-list-select">
    <MultiListSelect
      :list="list"
      :multiple="multiple"
      :optionValue="optionValue"
      :optionText="optionText"
      :selectedItems="selectedItems"
      :class="customClass"
      @select="onSelect"
    />
    <!-- 自定义选中项展示区域 -->
    <div class="selected-items-display">
      <span
        v-for="(item, index) in displayedItems"
        :key="item[optionValue]"
        class="selected-item"
      >
        {{ item[optionText] }}
      </span>
      <span v-if="remainingCount > 0" class="more-label">
        +{{ remainingCount }} More
      </span>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    list: Array,
    multiple: Boolean,
    optionValue: String,
    optionText: String,
    selectedItems: Array,
    customClass: String,
    // 可配置最多显示几个选中项,超出则显示+N
    showMaxItems: {
      type: Number,
      default: 2
    }
  },
  computed: {
    // 获取要显示的前N个选中项
    displayedItems() {
      return this.selectedItems.slice(0, this.showMaxItems);
    },
    // 计算剩余未显示的选中项数量
    remainingCount() {
      return this.selectedItems.length - this.showMaxItems;
    }
  },
  methods: {
    onSelect(selected) {
      this.$emit('select', selected);
    }
  }
};
</script>

<style scoped>
.custom-multi-list-select {
  position: relative;
}

/* 隐藏组件默认的选中标签 */
.custom-multi-list-select :deep(.vue-search-select-multiple .selected-tag) {
  display: none;
}

/* 调整输入框内边距,避免自定义内容被遮挡 */
.custom-multi-list-select :deep(.vue-search-select-input) {
  padding: 4px 28px 4px 8px;
  min-height: 32px;
}

/* 将自定义选中项区域定位到选择框内部 */
.selected-items-display {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 6px;
  padding: 4px 28px 4px 8px;
  pointer-events: none; /* 不干扰选择框的点击交互 */
}

/* 选中项样式 */
.selected-item {
  background-color: #e5e7eb;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 14px;
  color: #374151;
}

/* "+N More"提示样式 */
.more-label {
  font-size: 14px;
  color: #6b7280;
}
</style>

关键要点

  • 使用:deep()穿透scoped样式,隐藏组件默认的选中项标签
  • 通过绝对定位将自定义展示区域嵌入选择框内部,设置pointer-events: none避免干扰组件原有交互
  • 通过计算属性控制显示的选中项数量,超出部分显示"+N More"提示
  • 可通过showMaxItems属性配置最多显示的选中项数量,灵活调整展示效果

内容的提问来源于stack exchange,提问作者ajo_sam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 12:15:11