如何使用JavaScript创建动态测验?

时间:2016-08-02 19:10:26

标签: javascript html vue.js

我正在尝试进行测验,用户将会收到一张"卡"简单的是/否问题和一些多项选择问题的界面。在回答一个问题时,接下来的问题会改变以适应之前的答案。

示例流程:

你想外出就餐吗?我想吃饭。你想在韩国餐馆吃饭吗?是。

我遇到的问题是我希望在前端没有多条路线。目前,我正在使用Vue.js和Vue-Router。这就是我所拥有的(不要介意命名约定,只是暂时的):

<template>

  <div>
    <div v-show="isQuestion(0)">
      <p id="question_1">Question 1</p>

      <p @click="answerQuestion()">Answer 1</p>
      <a @click="answerQuestion()">Answer 2</a>
    </div>

    <div v-show="isQuestion(1)">
      <p id="question_2">Question 2</p>

      <div v-show="isAnswer(0)">
        <p>Game?</p>
        <a @click="answerQuestion()">Yes</a>
        <a @click="nextAnswer()">No</a>
      </div>

      <div v-show="isAnswer(1)">
        <p>Read?</p>
        <a @click="answerQuestion()">Yes</a>
        <a @click="nextAnswer()">No</a>
      </div>

      <div v-show="isAnswer(2)">
        <p>Redo?</p>
        <a @click="resetAnswer()">Reset</a>
      </div>
      <a @click="search()">Search</a>
    </div>
  </div>

</template>

<script>
  export default {
    data () {
      return {
        question: 0,
        answer: 0,
        answers: {}
      }
    },
    methods: {
      answerQuestion () {
        this.answers[this.question] = this.answer
        this.question++
        this.answer = 0
      },
      nextAnswer () {
        this.answer++
      },
      resetAnswer () {
        this.answer = 0
      },
      isQuestion (n) {
        return n === this.question
      },
      isAnswer (n) {
        return n === this.answer
      }
    }
  }
</script>

我想到的一个选择可能是将问题与答案放在数据库中,以便前端可以将它们作为JSON获取,然后填充所谓的&#34;卡&#34;。但后来我遇到了如何显示&#34;正确&#34;下一个问题回答了以前的答案。

我不觉得对所有内容进行硬编码感觉很舒服,因为这似乎是一种不好的做法,但我很难以其他方式做这件事。

1 个答案:

答案 0 :(得分:2)

我认为您的案例的重点是正确的数据结构。在你的情况下,我将使用:

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
     ]
   }
}

使用这一系列问题,您可以使用Vue以自动方式呈现它(您可以从ajax json中读取它),显示下一个问题和其他内容。如果某些问题的回答是NULL,那么你知道这是下一个问题&#39;展示......

在您的vue组件中创建变量curentQuesionIndex=2currentQuestion= {..},您将使用它来显示,保存(进入您的查询数组)并进行操作(例如&#39; special&#39; answer喜欢&#39;重置&#39;)。

您只能使用一个@click功能:saveAnswer(value)其中&#39;值&#39;是来自question.options的一个选项。在这个函数中你可以保存问题列表的答案,将newq问题设置为currentQuestion变量(在屏幕上呈现)并依赖于value你将做出不同的操作 - 例如:你将把if语句那里:如果问题[currentQuestionIndex] .options [value] ==&#39; reset&#39;然后你会重置......