0

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>
1
  • Cause you're using same variable(acertou ) for all elements. Try to use unique identifier. Commented Jul 31, 2021 at 0:32

2 Answers 2

1

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.

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

4 Comments

It is the same answer with mine
@omerS Nope, it's different. I am here using 'index' of the loop as unique identifier without implementing any methods. Why call a method when you can directly assign the unique identifier to a variable?
because there is a method in the example. So I thought putting it in that method would be better.
@omerS - yea sure but it's always better to provide a cleaner and efficient code while helping or guiding someone :)
1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.