Vue.js второй переключатель выбирается при загрузке приложения

#javascript #css #vue.js

#javascript #css #vue.js

Вопрос:

У меня есть следующий тест, написанный с использованием Vue.js где все работает как по волшебству…

кроме одной вещи, которую я не могу найти решение, это мой код, вызывающий эту ошибку? или мне нужно подойти к этому по-другому?

Обновление: теперь, когда я добавил уникальные имена для каждого элемента, как следует из одного из ответов, второй пункт меню всегда выбирается по умолчанию при загрузке страницы … есть какие-либо подсказки о том, как преодолеть эту проблему?

 <script>

    // Create a quiz object with a title and two questions.
// A question has one or more answer, and one or more is valid.
var quiz = {
   "title":"Quizorama",
   "questions":[
      {
         "text":"Lalala",
         "audio":"TextTo-1-1.mp3",
         "responses":[
            {
               "text":"Incorrect"
            },
            {
               "text":"Incorrect"
            },
            {
               "text":"Correct",
               "correct":true
            }
         ]
      },
      {
         "text":"Something",
         "audio":"57633709.mp3",
         "responses":[
            {
               "text":"Correct",
               "correct":true
            },
            {
               "text":"Incorrect"
            },
            {
               "text":"Incorrect"
            }
         ]
      },
      {
         "text":"Question",
         "audio":"57633709.mp3",
         "responses":[
            {
               "text":"Correct",
               "correct":true
            },
            {
               "text":"Incorrect"
            },
            {
               "text":"Incorrect"
            }
         ]
      }
   ]
};


</script>


<div class="wrapper" id="page-wrapper">

    <div class="centered-content " id="content" tabindex="-1">

        <div class="row">
            <main class="site-main" id="main">


  <div id="app">
  <h1>{{ quiz.title }}</h1>
  <!-- index is used to check with current question index -->
  <div v-for="(question, index) in quiz.questions">
    <!-- Hide all questions, show only the one with index === to current question index -->
     <transition name="slide-fade"> 
    <div v-show="index === questionIndex">
      <h2>{{ question.text }}</h2>
      <audio width="450" controls :src="question.audio"></audio>

      <ul>
    <li v-for="response in question.responses" 
        v-bind:correctOrNot="response.correct"
        v-bind:class="{ active: isActive }">
      <label>
             <input type="radio" 
               v-bind:value="checkResponse(response.correct)"  
               v-bind:name="nameMethod(index ,response.text, 
               questionIndex)" 
               v-model="userResponses[index]"
               > {{response.text}}
               
      </label>
    </li>
</ul>
      <!-- The two navigation buttons -->
      <!-- Note: prev is hidden on first question -->
      <!-- <button v-if="questionIndex > 0" v-on:click="prev">
        otra oportunidad?
      </button> -->
      <button v-on:click="next">
            Next pleeeeease!
          </button>

    </div>
 </transition>

  </div>
  <transition name="slide-fade"> 

  <div v-show="questionIndex === quiz.questions.length">
    <h3>
yer results are da following bro:
</h3>
    <p class="puntaje">
     {{ score() }} 
    </p>


  </div>
  </transition> 

</div>

<script>


      
new Vue({
  el: '#app',

  data: {
    quiz: quiz,
    // Store current question index
    questionIndex: 0,
    // An array initialized with "false" values for each question
    // It means: "did the user answered correctly to the question n?" "no".
    userResponses: Array(quiz.questions.length).fill(false),
    isActive: false,
   
  },

  // The view will trigger these methods on click
  methods: {


checkResponse: function(response){
  let checkResponseValue = response; 
  if (response == true){
    return true;
  } else {
    return false;
  }
},
nameMethod: function(index, responseText, questionIndex){
  var index = index;
  var questionIndexValue = questionIndex
  var responseText = responseText;
  var name = index   responseText '_'  questionIndexValue;
  return name;
},

    next: function() {    
      
      console.log(this);

      this.isActive = true;

      setTimeout(() => {
        // move to next question 
       this.questionIndex  ;

       this.isActive = false;

      }, 3000);

    },

    updateMessage: function () {
      this.message = 'updated';
      },
    
    // Go to previous question
    prev: function() {
      this.questionIndex--;
    },
    editModal: function(id){
        console.log(id);
    },

    // Return "true" count in userResponses
    score: function() {
     let scorePercent = Math.round(this.userResponses.filter(function(val) { return val }).length * 100 / this.questionIndex);
     let newResu<
    
     if(scorePercent == 0 ){
      newResult =  "you suck , not even one good response mate ";
      return newResult
     }

     if(scorePercent < 30){
      newResult = scorePercent   "% Was Good, so you need to practice more mate";
      return newResult
     }

     if(scorePercent < 70){
      newResult =  scorePercent   "% yar a ducking star but there is more to improve";
      return newResult
     }

     if(scorePercent == 100){
      newResult = scorePercent   "% you are a godlike creature made flesh";
      return newResult
     }
     
      }

  }


});

</script>


<style>

p.puntaje {
    font-size: 25px;
    color: #333333;
    margin-bottom: 40px;
    background: #fce373;
    padding: 13px;
    border-radius: 100px;
    text-align: center;
}

main#main {
    margin: auto;
}
#app h1 {
    font-size: 66px;
    font-weight: 900;
    color: #b1b1b1;
}

#app h2 {
    font-size: 125px;
    color: #a282bb;
}

#app ul {
    list-style: none;
    padding: 0;
}

/* Enter and leave animations can use different */
/* durations and timing functions.              */
.slide-fade-enter-active {
  transition: all 0.5s ease;
  transition-delay: 2s;

}
.slide-fade-leave-active {
  transition: all 0.5s cubic-bezier(1.0, 0.5, 0.8, 1.0);
}
.slide-fade-enter
/* .slide-fade-leave-active below version 2.1.8 */ {
  transform: translateX(10px);
  opacity: 0;
  transition: all 0.5s ease;


}
#app button {
    background: #00BCD4;
    width: 200px;
    margin-bottom: 30px;
    border-radius: 100px;
    font-size: 17px !important;
    padding: 7px 17px;
    border: none;
}
#app li label {
    font-size: 25px;
    background: #fff2b6;
    border-radius: 100px;
    padding-left: 17px;
    padding-right: 17px;
    margin-top: 16px;
    padding-top: 5px;
    transition: all 0.5s ease;
}

#app li label:hover{
background: #fce372;
cursor:pointer;
transition: all 0.5s ease;

}

li.active label {
    background: #ee734c !important;  transition: all 0.5s ease;

}
li[correctOrNot="true"].active label {
  background: #9ad18b !important;  transition: all 0.5s ease;

}

.slide-fade-leave-to
/* .slide-fade-leave-active below version 2.1.8 */ {
  transform: translateX(50px);
  opacity: 0;
  transition: all 0.5s ease;

}
</style>
  

Ответ №1:

Это простая проблема с HTML. Вы определяете переключатели со response.correct значением, которое не определено для неправильных параметров, а также идентично для обоих (независимо от того, является ли оно нулевым или ложным).

Ваш вывод может быть таким:

 <input type="radio" name="index">Incorrect
<input type="radio" name="index">Incorrect
<input type="radio" name="index" value="true">Correct
  

Если у вас есть группа переключателей, и несколько из них имеют одинаковое значение (или ни одного), это, по сути, один и тот же ввод. Попробуйте определить уникальное значение для каждой переключающей кнопки с одинаковым именем.

Комментарии:

1. Это не сработало, я добавил вычисляемые функции для создания уникального имени и значений для каждой из переключателей, но теперь вторая кнопка автоматически выбирается при загрузке страницы. я обновляю свой код в вопросе, чтобы отразить isuse.

2. @Herzling В этом ответе предлагается добавить уникальные значения, а не уникальные имена. Из того, что я могу сказать, вы этого не сделали.

3. Вы были правы @Daedalus, мне пришлось обновить свой код, чтобы заставить его работать, но предоставление уникальных значений наконец сработало… Мне пришлось адаптировать код, чтобы «подобрать» количество правильных ответов, но это определенно было вызвано отсутствием значений или идентичных значений. спасибо за вашу помощь.