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

VueJS下拉组件中如何实现选项前置彩色标签展示

cs-dashboard-select 选项前添加颜色标识实现方案

实现思路

自研下拉组件一般支持两种自定义渲染方式:作用域插槽自定义选项内容、options配置传入自定义虚拟节点,两种方式都可以实现选项前加颜色标识的效果,可根据组件实际支持的能力选择。

方式1:通过选项作用域插槽实现(推荐)

这是可维护性最高的方式,首先提前定义好排班类型和专属颜色的映射关系,再在插槽里渲染颜色块+选项文本即可。

  1. 先在脚本中定义颜色映射:
// 排班类型与对应颜色的映射表,可根据实际配色修改
const scheduleColorMap = {
  '1': '#52c41a', // On duty
  '2': '#1890ff', // On vacation
  '3': '#faad14', // Training
  '4': '#f5222d'  // Sick leave
}
  1. 在组件中使用选项插槽自定义渲染内容:
<cs-dashboard-select
  name="schedule_type"
>
  <!-- 选项作用域插槽,option为当前遍历的选项数据 -->
  <template #option="{ option }">
    <span 
      class="schedule-color-dot" 
      :style="{ backgroundColor: scheduleColorMap[option.value] }"
    ></span>
    <span>{{ option.label }}</span>
  </template>
  Select type
</cs-dashboard-select>

注意:不同封装版本的插槽名可能有差异,如果#option不生效,可以查看组件文档替换为对应的选项插槽名,常见命名还有#default、#optionItem。

  1. 添加对应样式:
.schedule-color-dot {
  display: inline-block;
  width: 12px;
  height: 12px;
  /* 要圆形标识就设为50%,方形设为0,圆角矩形设为2~4px即可 */
  border-radius: 2px;
  margin-right: 8px;
  vertical-align: middle;
}

如果需要选中后下拉框的回显文本前也展示颜色标识,只需要用相同的逻辑写选中值的自定义插槽即可,组件一般会提供对应的值渲染插槽,写法完全一致。

方式2:通过options传入自定义VNode实现

如果组件不支持自定义选项插槽,可以直接在options的label字段中传入Vue生成的虚拟节点,实现自定义渲染:

<script setup>
import { h } from 'vue'

// 直接在options配置中生成带颜色块的label内容
const scheduleOptions = [
  {
    value: '1',
    label: h('div', { style: { display: 'flex', alignItems: 'center' } }, [
      h('span', { style: { width: '12px', height: '12px', borderRadius: '2px', backgroundColor: '#52c41a', marginRight: '8px' } }),
      h('span', 'On duty')
    ])
  },
  {
    value: '2',
    label: h('div', { style: { display: 'flex', alignItems: 'center' } }, [
      h('span', { style: { width: '12px', height: '12px', borderRadius: '2px', backgroundColor: '#1890ff', marginRight: '8px' } }),
      h('span', 'On vacation')
    ])
  },
  {
    value: '3',
    label: h('div', { style: { display: 'flex', alignItems: 'center' } }, [
      h('span', { style: { width: '12px', height: '12px', borderRadius: '2px', backgroundColor: '#faad14', marginRight: '8px' } }),
      h('span', 'Training')
    ])
  },
  {
    value: '4',
    label: h('div', { style: { display: 'flex', alignItems: 'center' } }, [
      h('span', { style: { width: '12px', height: '12px', borderRadius: '2px', backgroundColor: '#f5222d', marginRight: '8px' } }),
      h('span', 'Sick leave')
    ])
  }
]
</script>

<template>
  <cs-dashboard-select
    :options="scheduleOptions"
    name="schedule_type"
  >
    Select type
  </cs-dashboard-select>
</template>

  • 颜色块的尺寸、圆角、间距都可以根据设计图的实际效果调整样式参数
  • 如果组件支持给选项传入自定义class,也可以提前写好不同类型的颜色样式class,给选项加上对应class实现效果,原理和上述方案一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 08:42:13