[Vuejs]-Vue 3 app bug: why is this method executed before any click event occurs?

3👍

UPDATED

checkAnswer() is invoked immediately if used outside a handler.

maybe this will help, when checkAnswer() is called, store the selected answer selectedAnswer and check if answer is correct isCorrect, and use these 2 states to compare the looped answers.

<li
  v-for="answer in answers"
  :key="answer"
  @click="checkAnswer(answer)"
  :class="{
    'text-white bg-success' : (selectedAnswer === answer && isCorrect),
    'text-white bg-danger' : (selectedAnswer === answer && !isCorrect)
  }"
>
  {{answer}}
</li>

data() {
    return {
        isCorrect: false,
        selectedAnswer: ''
        ...
    }
},
methods: {
  checkAnswer(answer) {
    // check if the clicked anwser is equal to the correct answer
    this.selectedAnswer = answer

    if (answer == this.results[this.questionCount]["correct_answer"]) {
      this.isCorrect = true
    } else {
      this.isCorrect = false
    }
  },
}

https://jsfiddle.net/renzivan15/fw10q5og/12/

2👍

This is executing it before the click:
:class="{'text-white bg-success' : checkAnswer(answer)}".
You’ll need to keep the state in a variable for each answer and update it within the method.
And as a side node, it is recommended to use :key for looped elements.

👤Thomas

1👍

The issue is that the checkAnswer is referenced in the html template so it will execute immediately on render. You might want to try instead setting the class to some computed property instead of the function.

<li v-for="answer in answers" @click="checkAnswer(answer)" :class="{'text-white bg-success' : checkAnswer(answer)}">{{answer}}</li>

Leave a comment