2

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?

1
  • You can use :class vue directive. Perhaps you need to refactor code. Show divs by v-for from array : [{class: 'light|dark', active: true|false: background: number}] Commented May 26, 2017 at 8:27

1 Answer 1

2

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>

Sign up to request clarification or add additional context in comments.

1 Comment

What if complicated logic has to be fullfilled in order to determine wether to change the class or not or to change it depending on the current state in different ways...?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.