VueJS add remove class on click

13,886

You could try something like this and swap out the color strings for objects to also get the light and dark class in there

new Vue({
  el: '#chooser',
  data: () => ({
    // generate the array as you want
    colors: [
      'green', '#000', '#123'
    ],
    activeColor: ''
  })
 })
.colors > div {
  width: 100px;
  height: 100px;
}

.active {
  border: 2px solid red;
}
<div id="chooser">
  <div class="choose-color__primary colors" style="width:400px">
      <div 
        v-for="color in colors" 
        @click="activeColor = color" 
        :style="{'background-color': color}"
        :class="{active: color === activeColor}"
       ></div>
  </div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.3/vue.min.js"></script>
Share:
13,886

Related videos on Youtube

hauge
Author by

hauge

Updated on September 14, 2022

Comments

  • hauge
    hauge over 1 year

    I have a "menu" with colors, and when the user click one of the div's, it should add an active class, and remove all other active classes from the others div... How do I do this in VUE?

    <div class="choose-color__primary" style="width:400px">
                                <div class="light" v-on:click="selectColor($event)" :style="{'background-color': LightenDarkenColor(colors.primaryColor, 30)}"></div>
                                <div class="light" v-on:click="selectColor($event)" :style="{'background-color': LightenDarkenColor(colors.primaryColor, 15)}"></div>
                                <div class="light" v-on:click="selectColor($event)" :style="{'background-color': LightenDarkenColor(colors.primaryColor, 0)}"></div> <!-- This is the color the user has chosen from color wheel -->
                                <div class="dark" v-on:click="selectColor($event)" :style="{'background-color': LightenDarkenColor(colors.primaryColor, -15)}"></div>
                                <div class="dark" v-on:click="selectColor($event)" :style="{'background-color': LightenDarkenColor(colors.primaryColor, -30)}"></div>
                            </div>
    

    I know that i in my selectColor() function could do something like:

    event.target.parentNode.classList.remove("active");
                event.target.className = "active";
    

    However, just thought there was a better way in VUE than manipulating the DOM directly this this?