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

Vue+Element UI el-select选中current项如何展示自定义Current标签

实现方案

第一步:新增计算属性获取当前选中的完整选项

在你的Vue实例中添加computed配置,用于根据选中的value匹配对应的完整选项数据,方便判断是否需要显示Current胶囊:

var Main = {
  data() {
    return {
      drawer: {
        form: {
          period: null
        }
      },
      data : [
        {
          label: "JAN to MAR 2021",
          value: "1",
          current: true
        }, {
          label: "Apr to Jun 2021",
          value: "2",
          current: false
        }, {
          label: "Jul to Sep 2021",
          value: "3",
          current: false
        }, {
          label: "Oct to Dec 2021",
          value: "4",
          current: false
        }
      ]
    }
  },
  // 新增计算属性
  computed: {
    selectedItem() {
      return this.data.find(item => item.value === this.drawer.form.period) || {}
    }
  },
  methods: {}
}
var Ctor = Vue.extend(Main);
new Ctor().$mount('#app');

第二步:自定义el-select的选中项显示插槽

修改HTML部分的el-select代码,使用Element UI提供的label作用域插槽自定义输入框内的显示内容,根据选中项的current属性动态控制胶囊显示:

<script src="//unpkg.com/vue/dist/vue.js"></script>
<script src="//unpkg.com/element-ui@2.4.11/lib/index.js"></script>
<div id="app">
<el-select v-model="drawer.form.period" value-key="value">
  <!-- 新增自定义选中内容插槽 -->
  <template slot="label" slot-scope="{ label }">
    <span>{{ label }}</span>
    <div v-if="selectedItem.current" class="capsule secondary" style="margin-left: 8px;">Current</div>
  </template>
  <el-option
    v-for="item in data"
    :key="item.value"
    :label="item.label"
    :value="item.value">
    <span>{{ item.label }}</span>
    <div v-if="item.current" class="capsule secondary" style="margin-left: 8px;">Current</div> 
  </el-option>
</el-select>
</div>
  • 注:原代码中固定显示Current的suffix插槽可以直接删除,避免重复显示胶囊。

第三步:可选样式调整

如果出现文字和胶囊排版不对齐的问题,新增以下CSS即可:

@import url("//unpkg.com/element-ui@2.4.4/lib/theme-chalk/index.css");
.capsule {
    background: #e6e9f0;
    border-radius: 7.5px;
    height: 15px;
    line-height: 15px!important;
    color: #04246a;
    font-size: 10px;
    text-align: center;
    display: inline-block;
    padding: 0 6px;
    letter-spacing: .5px;
    text-transform: uppercase;
    max-width: 100%;
    text-overflow: ellipsis;
    overflow: hidden;
    word-break: normal;
    word-wrap: normal;
}
/* 新增对齐样式 */
.el-select .el-input__inner {
  display: flex;
  align-items: center;
}

修改完成后,选中带current: true的选项时,输入框内就会同步显示Current胶囊,选中非current选项时胶囊自动隐藏,符合预期效果。


内容的提问来源于stack exchange,提问作者Renaud is Not Bill Gates

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 19:24:02