mardi 7 mars 2017

Checkbox statuses not persisted in simple vue.js questionnaire app

I wrote this simple questionnaire app example: http://ift.tt/2naS6ns but I have problem with checkboxes loosing its state when user clicks buttons "Next" and "Back".

For example, if user performs this actions:

  1. answer with "Lisp" on first question,
  2. click "Next",
  3. answer with "Bill Gates" on second question,
  4. click "Back",
  5. click "Next",

then you'll see that the "Bill Gates" checkbox will not be checked anymore, despite the fact that backing array userAnswers is correctly updated.

I cannot understand why that's happen and what I should change in my code to made it work correctly.

Here's the code:

<html>
<head>
<title>Questionnaire</title>
<script src="vue.js"></script>
</head>
<body>
<h1>Questionnaire</h1>
<div id="app">
  <p><b>Question )</b> </p>
  <div v-for="ans in currQuestion.answers">
    <input type="radio"
           :name="currQuestionIndex"
           :value="ans"
           v-model="userAnswers[currQuestionIndex]" />
    <label :for="ans"></label><br>
  </div>
  <p>
  <button @click="goBack">Back</button>
  <button @click="goNext">Next</button>
  </p>
  userAnswers = 
</div>
</body>
<script>
var app = new Vue({
  el: '#app',
  data: {
    currQuestionIndex: 0,
    questions: [
        {text: "What's the name of most powerful programming language?",
         answers: ['Java', 'C#', 'Lisp', 'Haskell']
        },
        {text: 'Who is Microsoft founder?',
         answers: ['Bill Gates', 'Richard Stallman', 'Steve Jobs']
        },
        {text: 'What type of software do you like most?',
         answers: ['open source', 'closed source', 'public domain']
        },
        {text: 'The best computing company is:',
         answers: ['IBM', 'Microsoft', 'Google']
        },
    ],

    userAnswers: [null, null, null, null]
  },

  computed: {
    currQuestion: function () {
        return this.questions[this.currQuestionIndex];
    }
  },

  methods: {
    goNext: function(e) {
        var next = this.currQuestionIndex + 1;
        if (next >= this.questions.length) {
            alert("Ok, your answers are: " + this.userAnswers);
        } else {
            this.currQuestionIndex = next;
        }
    },
    goBack: function(e) {
        var previous = this.currQuestionIndex - 1;
        if (previous >= 0) {
            this.currQuestionIndex = previous;
        }
    }
  }
});
</script>
</html>




Aucun commentaire:

Enregistrer un commentaire