In this tutorial, we will learn and explore the fundamental concepts of how can we develop a frontend quiz app using VueJS. We all know how famous the VueJS framework is. Watch the below video to get idea of what are we developing.
So, without further ado, let’s get started with coding.
Here, we will be using Vue 2. Run the below command to create the VueJs app.
You’ll see something like this.
Now, with the help of the following command navigate to the directory and run the server.
The localhost will display the default screen as shown below.
Every Vue component consists of three sections:
Explanation
The logic will have two methods
1. handle Quiz completed ( ) : It receives the user score from the Quiz component and sets it to local state ‘this . score’. It is triggered by the custom event ‘quiz-completed’ that we’ve ] defined in the Quiz component.
2. update Quiz( ): The method will bind key to the ‘quiz Key’ data property. It will increment the ‘quiz Key’ by one that is further triggered by the ‘reload’ event from the CustomModal component.
Further moving ahead with our tutorial to develop frontend quiz app using VueJS. Next we will start with our components: Quiz Component and CustomModal Component.
The file CustomModal.vue will consist the UI and logic code of the modal. Refer to the code below.
{{ header }}
{{ subheader }}
You answered {{ Math.floor( (score.correctlyAnsweredQuestions / score.allQuestions) * 100 ) }} % correctly! Answered {{ score.correctlyAnsweredQuestions }} out of {{ score.allQuestions }} questions.
Explanation
Here’s the code for the Quiz component.
You have {{ correctAnswers }} correct {{ pluralizeAnswer }}!Currently at question {{ index + 1 }} of {{ questions.length }}
Explanation
Here’s the logic part of the Quiz component. Let’s pick a method one at a time and see what the logic is about.
The prop ‘questions’ is intialized with an empty array. When the ‘loading’ is true, using Trivia API, we will fetch the questions and when the component will mount we will push them to the array. Here, five questions will be fetched every time an API call is made.
async fetchQuestions() { this.loading = true; //fetching questions from API let response = await fetch( "https://opentdb.com/api.php?amount=5&category=21&type=multiple" ); let index = 0; //To identify single answer let data = await response.json(); let questions = data.results.map((question) => { question.answers = [ question.correct_answer, ...question.incorrect_answers, ]; //shuffle above array for (let i = question.answers.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [question.answers[i], question.answers[j]] = [ question.answers[j], question.answers[i], ]; } //add right answers and key question.rightAnswer = null; question.key = index; index++; return question; }); this.questions = questions; this.loading = false; },
The computed property currentQuestion() will return the current question at the current index.
currentQuestion() { if (this.questions !== []) { return this.questions[this.index]; } return null; },
The below code snippet is to keep count of the correct answers.
correctAnswers() { if (this.questions && this.questions.length > 0) { let streakCounter = 0; this.questions.forEach(function (question) { if (!question.rightAnswer) { return; } else if (question.rightAnswer === true) { streakCounter++; } }); return streakCounter; } else { return "--"; } },
The below logic will calculate score. The ‘score()’ will use a reducer array prototype to reduce the current questions array to a n number. It returns the ‘score’ object that we use in the customModal component.
score() { if (this.questions !== []) { return { allQuestions: this.questions.length, answeredQuestions: this.questions.reduce((count, currentQuestion) => { if (currentQuestion.userAnswer) { // userAnswer is set when user has answered a question, no matter if right or wrong count++; } return count; }, 0), correctlyAnsweredQuestions: this.questions.reduce( (count, currentQuestion) => { if (currentQuestion.rightAnswer) { // rightAnswer is true, if user answered correctly count++; } return count; }, 0 ), }; } else { return { allQuestions: 0, answeredQuestions: 0, correctlyAnsweredQuestions: 0, }; } },
We will keep watcher on quizCompleted() and if the quiz is completed, it will emit the event and display the score using this.score to App component.
watch: { quizCompleted(completed) { completed && setTimeout(() => { this.$emit("quiz-completed", this.score); }, 3000); }, },
To check correct answer. For that, it will compare userAnswer, answer given by user, and correct_answer, answer given by API. It further sets ‘.rightAnswer’ and ‘.wrongAnswer’ accordingly and manages the index state for moving on to the next question.
checkCorrectAnswer(e, index) { let question = this.questions[index]; if (question.userAnswer) { if (this.index < this.questions.length - 1) { setTimeout( function () { this.index += 1; }.bind(this), 3000 ); } if (question.userAnswer === question.correct_answer) { /* Set class on Button if user answered right, to celebrate right answer with animation joyfulButton */ e.target.classList.add("rightAnswer"); /* Set rightAnswer on question to true, computed property can track a streak out of 20 questions */ this.questions[index].rightAnswer = true; } else { /* Mark users answer as wrong answer */ e.target.classList.add("wrongAnswer"); this.questions[index].rightAnswer = false; /* Show right Answer */ let correctAnswer = this.questions[index].correct_answer; let allButtons = document.querySelectorAll(`[index="${index}"]`); allButtons.forEach(function (button) { if (button.innerHTML === correctAnswer) { button.classList.add("showRightAnswer"); } }); } } },
After running the server, hit the browser and your UI will look something like this
On clicking the answer you will know whether your answer is correct or not and simultaneously display next question. At the end of the quiz you will have the score board that will display your correct answer(s).
Feel free to visit the github source code: VueJS Quiz App and clone the repository to play around with the code.
So, this was about how to develop frontend Quiz app using VueJS. Are you a keen learner for VueJS? If yes, then VueJS tutorials page is for you! Visit different tutorials and start diving deep in advanced VueJS knowledge or polish your fundamentals for VueJS as well.
Your Success Is Guaranteed !
We accelerate the release of digital product and guaranteed their success
We Use Slack, Jira & GitHub for Accurate Deployment and Effective Communication.