简体   繁体   中英

Mix order of answers in quiz Vue.js

Is it possible to mix order of answers in Vue.js? Now it is set up that first answer is correct and 2 wrong answers are second and third. Any solutions?

HTML:

<input placeholder="Question..." v-model="questionIn" type="text" />
<br />
<input placeholder="Right Answer..." v-model="answercorrectIn" type="text" />
<br />
<input placeholder="Bad Answer..." v-model="answerfalse1In" type="text" />
<br />
<input placeholder="Bad Answer..." v-model="answerfalse2In" type="text" />
<br />

And here is JS Vue:

    addQuestion()
        {
            if ((this.questionIn != "") && (this.answercorrectIn != "") && (this.answerfalse1In != "") && (this.answerfalse2In != ""))
            {
                this.questions.push(
                {
                    question: this.questionIn,
                    answers:
                    [
                        { id: 0, answer: this.answercorrectIn, correct: false },
                        { id: 1, answer: this.answerfalse1In, correct: false },
                        { id: 2, answer: this.answerfalse2In, correct: false }
                    ],
                    correct: [0],
                    false: [1, 2],

See this "shuffle answers" part in a very good vue.js tutorial, she is implementing exactly what you need, using the lodash shuffle function .

You can see there a full implementation to such feature with all the cases you should handle.

You could shuffle the answers in addQuestion() :

function shuffleArray(array) {
  for (let i = array.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1))
    const temp = array[i]
    array[i] = array[j]
    array[j] = temp
  }
}

export default {
  methods: {
    addQuestion() {
      if (/* ok to add */) {
        this.questions.push({
          question: this.questionIn,
          answers: shuffleArray([
            { id: 0, answer: this.answercorrectIn, correct: false },
            { id: 1, answer: this.answerfalse1In, correct: false },
            { id: 2, answer: this.answerfalse2In, correct: false }
          ]),
          correct: [0],
          false: [1, 2],
        })
      }
    }
  }
}

demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM