Vue Element UI dynamically changes el-select color

3.2k views Asked by At

I tried to modify el-select to match the color of el-option. The methods I search on the Internet always require me to modify the style scoped . It is a static method and cannot be changed dynamically.

Example: My expectation is when selecting "WIP" in the options will turn it into a yellow label in el-select.

My expectation is when I select "WIP" in the options, it will become a yellow label in el-select according to the color in the options.


The following is a rough demo I created in Codesandbox.

https://codesandbox.io/s/dynamically-change-el-select-color-based-on-status-v0u8d?file=/src/views/Editor.vue

Your kind assistance will be greatly appreciated, thank you very much.

2

There are 2 answers

0
Coleone On BEST ANSWER

After a ton of research, finally I found the solution. enter image description here

The following is a rough demo I created in Codesandbox. https://codesandbox.io/s/dynamically-change-el-select-color-based-on-status-v2-od8gn?file=/src/views/Editor.vue

I'm not sure if this is the best method, but this method has solved my problem. If you have a better solution, welcome to provide here.

Thank you very much!

3
dreijntjens On

You could set the class of the el-select based on that you could color the input value based on the selected value

<el-select
          v-model="scope.row.status"
          :class="getStatusColorClass(scope.row.status)"
          placeholder="Select"
        >
          <el-option
            v-for="(status, index) in statusList"
            :key="index"
            :label="status.name"
            :value="status.id"
          >
            <span :style="{ color: status.color }">{{ status.name }}</span>
          </el-option>
        </el-select>

JS:

  methods: {
    getStatusColorClass(id) {
      if (!id) {
        return {};
      }

      return this.statusList.find(status => status.id === id).name;
    }
  }

SCSS:

<style lang="scss">
.Approved input {
  color: #00A86B;
}
.Retake input {
  color: #ED2939;
}
.WIP input {
  color: #FCE205;
}
</style>