Home » vue » VueJS – Apply CSS class only to clicked element

VueJS – Apply CSS class only to clicked element

Posted by: admin November 26, 2021 Leave a comment

Questions:

I’m trying add a class to the correct answer. This code works, but when the key ‘acertou’ is true, CSS class ‘certa’ applies to all the li elements.

How can I add this class only to the li that was actually clicked?

<div class="alternativas">
      <ul>
        <li
          v-for="alternativa in perguntaAtual.alternativas"
          :key="alternativa"
          @click="corrige(alternativa, perguntaAtual)"
          :class="{ certa: acertou }"
        >
          {{ alternativa }}
        </li>
      </ul>
   </div>
Answers:

Try this way instead:

<div class="alternativas">
  <ul>
    <li
        v-for="(alternativa,index) in perguntaAtual.alternativas"
        :key="alternativa"
        @click="activeElement = index"
        :class="activeElement === index ? 'certa' : ''"
    >
        {{ alternativa }}
    </li>
  </ul>
</div>

export default {
  data() {
    return {
        activeElement: '',
    }
  },
}

On click, assign the index of the clicked element to a variable and apply the required class on the element where that variable and the index matches. You will require something unique for applying class or anything to a specific element. Here, index plays that role.

###

Maybe there is a better answer for this but I did exactly the same thing like this:


<div class="alternativas">
      <ul>
        <li
          v-for="alternativa in perguntaAtual.alternativas"
          :key="alternativa"
          @click="corrige(alternativa, perguntaAtual)"
          :class="[activeElement === alternativa ? 'acertou' : '']"
        >
          {{ alternativa }}
        </li>
      </ul>
</div>

export default {
 data() {
   return {
    activeElement: null,
  }
},
 methods: {
   corrige (alternativa) {
     this.activeElement = alternativa
    }
  }

}

Basically with your method you say that my activeElement is this and it checks if activeElement is same with your item so it gives class to only that item.