微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Vue 元素 UI - <el-select> 中的 html

如何解决Vue 元素 UI - <el-select> 中的 html

我想为每个条目实现一个带有不同颜色标签的选择元素:

enter image description here

我的代码如下:

var Main = {
  data() {
    return {
      selectedState: null,processstates: [
        {
          value: 0,label: 'New',color: 'ffffff'
        },{
          value: 1,label: 'Ready',color: 'ff9933'
        },{
          value: 2,label: 'Running',color: '008000'
        },{
          value: 3,label: 'Rejected',color: 'cc0000'
        },{
          value: 4,label: 'Terminated',color: '2E9AFE'
        }
      ]
    }
  },methods: {}
}

var Ctor = Vue.extend(Main);
new Ctor().$mount('#app');
@import url("//unpkg.com/element-ui@2.4.4/lib/theme-chalk/index.css");
<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="selectedState" style="width:200px">
      <el-option
        v-for="state in processstates"
        :key="state.value"
        :label="state.label"
        :value="state.value"
      >
        <span>
          <el-tag :style="'background-color:#' + state.color">&nbsp;</el-tag> {{ state.label }}
        </span>
      </el-option>
    </el-select>
</div>

如您所见,我设法将 html 注入选项标签并获得了所需的结果。
但是,我希望在选择一个选项时具有相同的 html。

想要的结果:

enter image description here

知道如何实现吗?

解决方法

您必须为此使用 prefix 槽。如下所示,我也将 selectedState 更改为对象,但您仍然可以使用 string 值,但是您必须进行查找才能获取颜色

var Main = {
  data() {
    return {
      selectedState: { color: 'ffffff'},processStates: [
        {
          value: 0,label: 'New',color: 'ffffff'
        },{
          value: 1,label: 'Ready',color: 'ff9933'
        },{
          value: 2,label: 'Running',color: '008000'
        },{
          value: 3,label: 'Rejected',color: 'cc0000'
        },{
          value: 4,label: 'Terminated',color: '2E9AFE'
        }
      ]
    }
  },methods: {}
}

var Ctor = Vue.extend(Main);
new Ctor().$mount('#app');
@import url("//unpkg.com/element-ui@2.4.4/lib/theme-chalk/index.css");

.el-input--prefix .el-input__inner { 
  padding-left: 40px;
}
<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="selectedState" value-key="value" style="width:200px">
  <template slot="prefix">
    <el-tag class="prefix" :style="`background-color: #${selectedState.color}`"/>
  </template>
  <el-option
    v-for="state in processStates"
    :key="state.value"
    :label="state.label"
    :value="state"
  >
    <span>
      <el-tag :style="'background-color:#' + state.color">&nbsp;</el-tag> {{ state.label }}
    </span>
  </el-option>
</el-select>
</div>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。