Search code examples
vue.jsselectvuejs2colorsdropdown

How to change color of default select option only and not other options in Vue?


I'm trying to apply a different colour (new color) for the default selected option "Please Select a Combo" and the other comboOptions "A", "B", "C", D" should be in color black.

I only want the disabled default option to be green, and all the other options to be black.

How do we do this? I've been trying to use conditional classes but it applies to all options and not just the first default one.

  <select
   v-model="comboSet"
   class="combo-padding"
   :class="{ 'new-color': comboSet !== null }"
  >
 <option value="" selected disabled hidden style="color: green"> 
   Please pick a combo
 </option>
 <option
           v-for="option in comboOptions"
           placeholder="Please Select a Combo"
           :value="option"
           :key="option"
           >
          {{ option }}
  </option>
</select>
 data () {
   comboOptions = ["A", "B", "C", D"] 
}
.new-color {
  color: green !important;
}

Thanks for the help!


Solution

  • Bearing in mind that select styling options are limited, you can apply classes to the option elements. Conditional styling can be applied like:

    <option
        v-for="(i, index) in items"
        :class="{ steely: styleMe == 1, purple: styleMe != 1 }"
        :key="index">
          {{ i }}
      </option>
    

    The template is:

    <template>
      <div>
        <h1>Select example</h1>
        <select
          :class="{ 'new-color': comboSet == 'Default option' }"
          v-model="comboSet">
          <option selected disabled class="new-color">Default option</option>
          <option
            v-for="(i, index) in items"
            :class="{ steely: styleMe == 1, purple: styleMe != 1 }"
            :key="index">
              {{ i }}
          </option>
        </select>
        <button @click.prevent="styleMe = !styleMe">Change</button>
      </div>
    </template>
    

    With data that looks like:

    data() {
      return {
        items: ["Option One", "Option Two", "Option Three"],
        styleMe: false,
        comboSet: "Default option",
      }
    }
    

    The styles look like:

    .new-color {
      color: green;
    }
    
    .steely {
      color: steelblue;
    }
    
    .purple {
      color: purple;
    }
    

    I created a more full example with conditional classes here: code sandbox select example VueJs

    Hope this make sense and answers the question.