Рандомно загружать вопросы и ответы в квизе на vue.js

Реализовываю квиз на vue.js. Подскажите, пожалуйста, хочу чтобы вопросы и ответы при загрузке каждый раз выводились в рандомном порядке.

main.js

function shuffleVueArray(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;
  }
}

const app = Vue.createApp({
  data() {
    return {
      idx: 0,
      selectedAnswer: "",
      correctAnswers: 0,
      wrongAnswers: 0,
      count: 3,
      questions: [
        {
          question:
            "Question 1",
          answers: { a: "ka", b: "ga", c: "na", d: "pa" },
          correctAnswer: "b",
        },
        {
          question: "Question 2?",
          answers: { a: "2005", b: "2008", c: "2003", d: "2004" },
          correctAnswer: "d",
        },
        {
          question:
            "Question 3",
            answers: { a: "1", b: "2", c: "3", d: "3" },
          correctAnswer: "b",
        },
      ],
      
    };
  },
  methods: {
    answered(e) {
      this.selectedAnswer = e.target.value;
      if (this.selectedAnswer == this.questions[this.idx].correctAnswer) {
        this.correctAnswers++;
      } else {
        this.wrongAnswers++;
      }
    },
    nextQuestion() {
      this.idx++;
      this.selectedAnswer = "";
      document.querySelectorAll("input").forEach((el) => (el.checked = false));
    },
    showResults() {
      this.idx++;
    },
    resetQuiz() {
      this.idx = 0;
      this.selectedAnswer = "";
      this.correctAnswers = 0;
      this.wrongAnswers = 0;
    },
   
    randomize() {
      let result = Object.keys(this.questions[this.idx].answers).map((key) => [Number(key), this.questions[this.idx].answers[key]]);
      shuffleVueArray(result);
      console.log(result)
    },
  },
  mounted() {
    shuffleVueArray(this.result);
  },
});




app.mount("#app");

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="./styles.css" />
    <link
      rel="stylesheet"
      href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta2/css/all.min.css"
      integrity="sha512-YWzhKL2whUzgiheMoBFwW8CKV4qpHQAEuvilg9FAn5VJUDwKZZxkJNuGM4XkWuk94WCrrwslk8yWNGmY1EduTA=="
      crossorigin="anonymous"
      referrerpolicy="no-referrer"
    />
    <style>
        footer {
            margin: 0 0 2rem;
        }
        i.fab:hover {
            opacity: 0.9;
        }
    </style>
    <title>Simple Quiz</title>
  </head>

  <body class="antialiased text-gray-700 bg-gray-100">
    <div id="app" class="flex w-full h-screen justify-center items-center">
      <div class="w-full max-w-xl p-3">
        <h1 class="font-bold text-5xl text-center text-indigo-700">
          Simple Quiz
        </h1>
        <div class="bg-white p-12 rounded-lg shadow-lg w-full mt-8">
          <div v-if="idx < count">
            <p class="text-2xl font-bold">{{questions[idx]['question']}}</p>
            <label
              v-for="(answer, index) in questions[idx].answers"
              :key="index"
              :for="index"
              class="block mt-4 border border-gray-300 rounded-lg py-2 px-6 text-lg"
              :class="{'hover:bg-gray-100 cursor-pointer' : selectedAnswer == ''}, {'bg-green-200' : index == questions[idx].correctAnswer && selectedAnswer != ''}, {'bg-red-200' : selectedAnswer == index}"
            >
              <input
                :id="index"
                type="radio"
                class="hidden"
                :value="index"
                @change="answered($event)"
                :disabled="selectedAnswer != ''"
              />
              {{answer}}
            </label>
            <div @click="randomize">клик</div>
            <div class="mt-6 flow-root">
              <button
                @click="nextQuestion"
                v-show="selectedAnswer != '' && idx < count - 1"
                class="float-right bg-indigo-600 text-white text-sm font-bold tracking-wide rounded-full px-5 py-2"
              >
                Next &gt;
              </button>
              <button
                @click="showResults"
                v-show="selectedAnswer != '' && idx == count - 1"
                class="float-right bg-indigo-600 text-white text-sm font-bold tracking-wide rounded-full px-5 py-2"
              >
                Finish
              </button>
            </div>
          </div>
          <div v-else>
            <h2 class="text-bold text-3xl">Results</h2>
            <div class="flex justify-start space-x-4 mt-6">
              <p>
                Correct Answers:
                <span class="text-2xl text-green-700 font-bold"
                  >{{correctAnswers}}</span
                >
              </p>
              <p>
                Wrong Answers:
                <span class="text-2xl text-red-700 font-bold"
                  >{{wrongAnswers}}</span
                >
              </p>
            </div>
            <div class="mt-6 flow-root">
              <button
                @click="resetQuiz"
                class="float-right bg-indigo-600 text-white text-sm font-bold tracking-wide rounded-full px-5 py-2"
              >
                Play again
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <script src="https://unpkg.com/vue@next"></script>
    <script type="module" src="./main.js"></script>
 
  </body>
</html>

Я добавил функцию shuffleVueArray. Добавил метод randomize. Повесил его на кнопку "Клик". При клике в консоли все отрабатывает. А как сделать чтобы рандом запускался после загрузки самого квиза. Добавил mounted, но все равно вопросы и ответы всегда загружаются в одном и том же порядке. Понимаю, что нужно здесь v-for="(answer, index) in questions[idx].answers" выводить по другому, но не пойму как. Спасибо!

update Вопрос c рандомной загрузкой решил так. Добавил новую функцию.

function shuffle(array) {
  let currentIndex = array.length,  randomIndex;

  // While there remain elements to shuffle.
  while (currentIndex != 0) {

    // Pick a remaining element.
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex--;

    // And swap it with the current element.
    [array[currentIndex], array[randomIndex]] = [
      array[randomIndex], array[currentIndex]];
  }

  return array;
}

и вместо questions: --> [ questions: shuffle([

осталось решить вопрос с перемешиванием ответов


Ответы (0 шт):