2

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],
Wenfang Du
  • 8,804
  • 9
  • 59
  • 90

2 Answers2

0

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.

shirulaf
  • 11
  • 2
0

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

tony19
  • 125,647
  • 18
  • 229
  • 307