Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

417
Visualizações
How to style a singular v-for item in vue, based on a condition?

I am making a multiple choice quiz game and want what the user clicked to change to either red or green depending on if that answer is correct or incorrect. I made a variable called selected which is what the user pressed- this does correctly update. I have also got all of the v-for items to change to the same colour depending on if the answer is correct or not, I only need help separating it so that only one of the v-for things change colour.

Here is my relative HTML:

<button type="button" class="btn" class="answer" v-for="option in options" @click="checkAnswer(option)" @click="selected = option" :style="{backgroundColor: colour}">
    {{option}}<br/>
  </button>
  <button type="button" @click="getQ" @click="shuffle(options)" class="btn button next">Next</button>
  

Here is the relative JS:

  let colour = Vue.ref('');
  let selected = Vue.ref('');
  let options = Vue.ref([correctAnswer, incorrectAnswerOne, incorrectAnswerTwo, incorrectAnswerThree]);

  // Methods

   let shuffle = function(options) {
     let num = options.length, t, raInt;
     //while there are remaining elements to shuffle
        while (num) {
          //choose random
          raInt = Math.floor(Math.random() * num--);
          //swap with current element
          t = options[num];
          options[num] = options[raInt];
          options[raInt] = t;
        }
        return options;
   };

   let checkAnswer = function(clicked) {
     console.log(clicked.value);
     console.log(correctAnswer.value);
     if (clicked.value == correctAnswer.value) { // checks if the button that was clicked is the same as the answers value
       this.result = "Correct!"; //if it does, result changes to Correct!
       this.colour = "green";
    } else {
       this.result = "Incorrect!"; //if the answer is incorrect, result changes to Incorrect!
       this.colour = "red";
    };
   };

And here is some CSS:

 .answer {
   width: 100%;
   background-color: #dbdbdb;
   padding: 4% 2%;
   margin: 1 0;
 }

 .answer:hover {
   background-color: #c2c2c2
 }

I haven’t really tried that much. I’m not sure what to try. In a different project I did style a different div based on what other div was selected, but I am not sure how to change just one part of a v-for, or if it is even possible.

Thanks in advance

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can set condition for showing color style:

const { ref, computed } = Vue
const app = Vue.createApp({
  setup() {
    let correctAnswer = 3
    let incorrectAnswerOne = 1
    let incorrectAnswerTwo = 2
    let incorrectAnswerThree = 4
    let colour = ref('');
    let selected = ref('');
    let options = ref([correctAnswer, incorrectAnswerOne, incorrectAnswerTwo, incorrectAnswerThree]);
    let shuffled = ref([])
    
    let shuffle = (array) => {
      selected.value = null
      let currentIndex = array.length,  randomIndex;
      while (currentIndex != 0) {
        randomIndex = Math.floor(Math.random() * currentIndex);
        currentIndex--;
        [array[currentIndex], array[randomIndex]] = [
          array[randomIndex], array[currentIndex]];
      }
      shuffled.value = array;
    };
    shuffle(options.value)

    let checkAnswer = function(clicked) {
      // 👇 set selected  
      selected.value = clicked
      if (clicked == correctAnswer) { 
        this.result = "Correct!";
        this.colour = "green";
      } else {
        this.result = "Incorrect!"; 
        this.colour = "red";
      };
    };
  
    return { colour, selected, options, shuffle, checkAnswer, shuffled }
  },
})
app.mount('#demo')
.answer {
   width: 100%;
   background-color: #dbdbdb;
   padding: .5em 2em;
   margin: 1 0;
 }

 .answer:hover {
   background-color: #c2c2c2
 }
 
 .btns {
  display: flex;
 }
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
  <div class="btns">
  <div v-for="(option, i) in shuffled" :key="i" >
                                                               <!-- 👇 condition -->
    <button class="answer" @click="checkAnswer(option)" :style="selected == option && {backgroundColor: colour}">
      {{option}}<br/>
    </button>
  </div>
  </div>
  <button type="button" @click="getQ, shuffle(options)" class="btn button next">Next</button>
</div>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda