[Vuejs]-How do I create a dynamic quiz using JavaScript?

2👍

I think the point on your case is proper data structure. In your case I will use:

data () {
  return {
     curentQuesionIndex: 0,
     curentQuesion: null,
     questions: [
       { 
         question: 'Do you want to eat out or at home?', 
         options: [{0:'No'}, {1:'Yes'}, {'special':'reset'}], // answer options
         answer: 1                   // if NULL then user not yet give answer
                                   // if 'special' then you process it differently

       },
       ... // next questions here
     ]
   }
}

Using this array of questions you can render it in automatic way using Vue, (you can read it from ajax json), show next questions and other stuff. If answer in some question is NULL then you know that this is the ‘next question’ to show…

In your vue component create variable curentQuesionIndex=2 and currentQuestion= {..} which you will use to show, save (into your query array), and operate (for instance of ‘special’ answer like ‘reset’).

You will use only one @click function: saveAnswer(value) where ‘value’ is the one option from question.options. Inside this funciotn you can save answer to questions list, set newq question to currentQuestion variable (which is rendered on screen) and depends of value you will make different actions – for instance: you will put if statement there: if questions[currentQuestionIndex].options[value] == ‘reset’ then you will reset…

Leave a comment