element-ui 中 el-select 组件 多选时,如何根据数据的属性自定义选中内容的背景颜色?



如何根据 options 中每个选项元素的 bgColor 属性来控制被选中的内容的不同的背景颜色呢?
就是达到上图的显示效果

<template>
  <el-select v-model="value1" multiple placeholder="请选择">
    <el-option
      v-for="item in options"
      :key="item.value"
      :label="item.label"
      :value="item.value">
    </el-option>
  </el-select>
</template>

<script>
  export default {
    data() {
      return {
        options: [{
          value: '选项1',
          label: 'aaa',
          bgColor:'#409EFF'
        }, 
        {
          value: '选项2',
          label: 'bbb',
          bgColor:'red'
        }, 
        {
          value: '选项3',
          label: 'ccc',
          bgColor:'orange'
        }, 
        {
          value: '选项4',
          label: 'ddd',
          bgColor:'yellow'
        }, 
        {
          value: '选项5',
          label: 'eee',
          bgColor:'brown'
        }],
        value1: [],
      }
    }
  }
</script>
阅读 7.1k
1 个回答

https://codepen.io/1567887123...

<template>
  <el-select v-model="value1" multiple class="tagStyle" placeholder="请选择" @change="change">
    <el-option
      v-for="item in options"
      :key="item.value"
      :label="item.label"
      :value="item.value" tags-size="mini"
      :style="{color:item.bgColor}">
    </el-option>
  </el-select>
</template>
var Main = {
  data() {
    return {
      tagStyleElem: "",
      options: [
        {
          value: "选项1",
          label: "aaa",
          bgColor: "#409EFF"
        },
        {
          value: "选项2",
          label: "bbb",
          bgColor: "red"
        },
        {
          value: "选项3",
          label: "ccc",
          bgColor: "orange"
        },
        {
          value: "选项4",
          label: "ddd",
          bgColor: "yellow"
        },
        {
          value: "选项5",
          label: "eee",
          bgColor: "brown"
        }
      ],
      value1: []
    };
  },
  methods:{
    change(){
      this.tagStyleElem.innerHTML = this.value1
      .map(
        (value, index) => `.tagStyle .el-tag:nth-child(${index + 1}) {color: #fff;background-color: ${this.options.find(item=>value == item.value)?.bgColor};}`)
      .join("");
    }
  },
  created() {
    this.tagStyleElem = window.document.head.appendChild(
      document.createElement("style")
    );
    
  }
};
var Ctor = Vue.extend(Main);
new Ctor().$mount("#app");

image.png

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题