SlideShare a Scribd company logo
1 of 47
Download to read offline
How to
Develop
Frontend
Quiz App
using
VueJS?


www.bacancytechnology.com
Tutorial Goal:
How to
Develop
Frontend
Quiz App
using VueJS
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.
Create VueJS
app
Here, we will be using Vue 2. Run the below
command to create the VueJs app.


vue create quiz-app
You’ll see something like this.
Now, with the help of the following
command navigate to the directory and run
the server.
cd quiz-add
npm run serve
The localhost will display the default screen
as shown below.
Create User
Interface
< template > containing HTML code of
the component
< script > containing business logic
< style > containing CSS code for styling
of the component
Quiz component
Modal component
Every Vue component consists of three
sections:


For our demo application, we will be having
two components:
Folder Structure


Here’s the image of our folder structure. It
will be a pretty simple structure.
Now let’s take a look at different files and
see what are we going to do. Keep the
note of the filename.
In search of dedicated VueJS
developers with extraordinary
problem-sloving skills and VueJS
expertise?
Contact Bacancy: the best
VueJS development company
and start developing your
project.
App.vue Set
Up
App.vue is the parent file of all the
components (here Quiz and Modal
component). Let’s define our components.
Refer to the following code for the UI
template.
<template>
<div id="app">
<h2>Quiz App</h2>
<quiz @quiz-
completed="handleQuizCompleted"
:key="quizKey" />
<custom-modal
v-show="showModal"
header="Congratulations!"
subheader="You've completed your
Quiz!"
:score="score"
@reload="updateQuiz"
@close="showModal = false"
/>
</div>
</template>
v – show=” show Modal” will render the
modal conditionally based on this .
showmodal.
The score is a dynamic prop sent to
modal from data properties.
The header and subheader are two static
props.
The reload and close are the custom
events that is called from modal-footer
Explanation


The code is quite simple.


.
Moving on the < script > tag.
<script>
import CustomModal from
"./components/CustomModal.vue";
import Quiz from "./components/Quiz.vue";
export default {
components: { Quiz, CustomModal },
name: "App",
data() {
return {
quizKey: 0,
showModal: false,
score: {
allQuestions: 0,
answeredQuestions: 0,
correctlyAnsweredQuestions: 0,
},
};
},
methods: {
handleQuizCompleted(score) {
this.score = score;
this.showModal = true;
},
updateQuiz() {
this.showModal = false;
this.quizKey++;
},
},
};
</script>
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.
Create
Components
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.
CustomModal.vue


The file CustomModal.vue will consist the
UI and logic code of the modal. Refer to the
code below.
<template>
<transition name="modal">
<div class="modal-mask">
<div class="modal-wrapper">
<div class="modal-container">
<div class="modal-header">
<h2>{{ header }}</h2>
<h3>{{ subheader }}</h3>
</div>
<div class="modal-body">
<div id="score">
You answered
<span class="highlight">
{{
Math.floor(
(score.correctlyAnsweredQuestions /
score.allQuestions) *
100
)
}}
% correctly!
</span>
Answered
<span class="highlight">
{{
score.correctlyAnsweredQuestions }} out
of
{{ score.allQuestions }}
</span>
questions.
</div>
</div>
<div class="modal-footer">
<button
id="play-again"
class="button-footer"
@click="$emit('reload')"
>
Play Again
</button>
<button
id="close-button"
class="button-footer"
@click="$emit('close')"
>
Close
</button>
</div>
</div>
</div>
</div>
</transition>
</template>
<script>
export default {
props: {
header: String,
subheader: String,
score: Object,
},
};
</script>
The score prop contains how many
questions the user answered correctly
and also contains total number of
questions.
We use the score prop received from the
Quiz component’s custom events. The
modal-footer will have two buttons
emitting custom events to reload and
close the modal.
Explanation
Quiz.vue


<template>
<div class="container">
<div class="correctAnswers">
You have
<strong>{{ correctAnswers }} correct
{{ pluralizeAnswer }}!</strong>
</div>
<div class="correctAnswers">
Currently at question {{ index + 1 }} of
{{ questions.length }}
</div>
<h1 v-html="loading ? 'Loading...' :
currentQuestion.question"></h1>
<!-- Only first question is displayed --
>
<form v-if="currentQuestion">
<button
v-for="answer in
currentQuestion.answers"
:index="currentQuestion.key"
:key="answer"
v-html="answer"
@click.prevent="handleClick"
></button>
</form>
</div>
</template>
“loading ? ‘Loading…’ :
currentQuestion.question” will check
the loading property and based on it will
decide ‘Loading…’ or the
currentQuestion.
The answer of every question will be
stored in the array answers. So, we will
loop the answers with the help of ‘v-for’
and display every answer as the button
element. With that, v-html=”answer”
will display answer on the button.
The logic will be executed by
handleClick that we will see later in the
script part.
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.
Fetch Questions


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=multipl
e"
);
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;
},
Display Current Question


The computed property currentQuestion()
will return the current question at the
current index.
currentQuestion() {
if (this.questions !== []) {
return this.questions[this.index];
}
return null;
},
Count Correct Answers


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 "--";
}
},
Calculate score


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,
};
}
},
Watcher on Quiz
Completion


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);
},
},
Check Correct Answer


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="${inde
x}"]`);
allButtons.forEach(function (button) {
if (button.innerHTML ===
correctAnswer) {
button.classList.add("showRightAnswer");
}
});
}
}
},
Run the
server
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).
Github
Repository:
VueJS Quiz
App
Feel free to visit the github source code:
VueJS Quiz App and clone the
repository to play around with the code.
Conclusion
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.
Thank You
www.bacancytechnology.com

More Related Content

Similar to How to develop frontend quiz app using vue js

Cognitive agent system to retrieve relevant code components from a repository
Cognitive agent system to retrieve relevant code components from a repositoryCognitive agent system to retrieve relevant code components from a repository
Cognitive agent system to retrieve relevant code components from a repositoryVenkat Projects
 
Vue fundamentasl with Testing and Vuex
Vue fundamentasl with Testing and VuexVue fundamentasl with Testing and Vuex
Vue fundamentasl with Testing and VuexChristoffer Noring
 
Angular Mini-Challenges
Angular Mini-ChallengesAngular Mini-Challenges
Angular Mini-ChallengesJose Mendez
 
JSLab. Алексей Волков. "React на практике"
JSLab. Алексей Волков. "React на практике"JSLab. Алексей Волков. "React на практике"
JSLab. Алексей Волков. "React на практике"GeeksLab Odessa
 
Mobile Open Day: React Native: Crossplatform fast dive
Mobile Open Day: React Native: Crossplatform fast diveMobile Open Day: React Native: Crossplatform fast dive
Mobile Open Day: React Native: Crossplatform fast diveepamspb
 
MVC Design Pattern in JavaScript by ADMEC Multimedia Institute
MVC Design Pattern in JavaScript by ADMEC Multimedia InstituteMVC Design Pattern in JavaScript by ADMEC Multimedia Institute
MVC Design Pattern in JavaScript by ADMEC Multimedia InstituteRavi Bhadauria
 
MT_01_unittest_python.pdf
MT_01_unittest_python.pdfMT_01_unittest_python.pdf
MT_01_unittest_python.pdfHans Jones
 
Angular Unit Testing NDC Minn 2018
Angular Unit Testing NDC Minn 2018Angular Unit Testing NDC Minn 2018
Angular Unit Testing NDC Minn 2018Justin James
 
Educate 2017: Customizing Assessments: Why extending the APIs is easier than ...
Educate 2017: Customizing Assessments: Why extending the APIs is easier than ...Educate 2017: Customizing Assessments: Why extending the APIs is easier than ...
Educate 2017: Customizing Assessments: Why extending the APIs is easier than ...Learnosity
 
Un-Framework - Delivering Dynamic Experiences with HTML over the Wire
Un-Framework - Delivering Dynamic Experiences with HTML over the WireUn-Framework - Delivering Dynamic Experiences with HTML over the Wire
Un-Framework - Delivering Dynamic Experiences with HTML over the WireAndreas Nedbal
 
Beginner’s tutorial (part 2) how to integrate redux-saga in react native app
Beginner’s tutorial (part 2) how to integrate redux-saga in react native appBeginner’s tutorial (part 2) how to integrate redux-saga in react native app
Beginner’s tutorial (part 2) how to integrate redux-saga in react native appKaty Slemon
 
How React Native, Appium and me made each other shine @ContinuousDeliveryAmst...
How React Native, Appium and me made each other shine @ContinuousDeliveryAmst...How React Native, Appium and me made each other shine @ContinuousDeliveryAmst...
How React Native, Appium and me made each other shine @ContinuousDeliveryAmst...Wim Selles
 
PT1420 Decision Structures in Pseudocode and Visual Basic .docx
PT1420 Decision Structures in Pseudocode and Visual Basic .docxPT1420 Decision Structures in Pseudocode and Visual Basic .docx
PT1420 Decision Structures in Pseudocode and Visual Basic .docxamrit47
 
Short Codes: Pain Free Magic
Short Codes: Pain Free MagicShort Codes: Pain Free Magic
Short Codes: Pain Free MagicMichael Susz
 
Asp netmvc e03
Asp netmvc e03Asp netmvc e03
Asp netmvc e03Yu GUAN
 
reactjs-quiz..docs.pdf
reactjs-quiz..docs.pdfreactjs-quiz..docs.pdf
reactjs-quiz..docs.pdfAyanSarkar78
 
Into React-DOM.pptx
Into React-DOM.pptxInto React-DOM.pptx
Into React-DOM.pptxRan Wahle
 

Similar to How to develop frontend quiz app using vue js (20)

Cognitive agent system to retrieve relevant code components from a repository
Cognitive agent system to retrieve relevant code components from a repositoryCognitive agent system to retrieve relevant code components from a repository
Cognitive agent system to retrieve relevant code components from a repository
 
Vue fundamentasl with Testing and Vuex
Vue fundamentasl with Testing and VuexVue fundamentasl with Testing and Vuex
Vue fundamentasl with Testing and Vuex
 
Angular Mini-Challenges
Angular Mini-ChallengesAngular Mini-Challenges
Angular Mini-Challenges
 
JSLab. Алексей Волков. "React на практике"
JSLab. Алексей Волков. "React на практике"JSLab. Алексей Волков. "React на практике"
JSLab. Алексей Волков. "React на практике"
 
Mobile Open Day: React Native: Crossplatform fast dive
Mobile Open Day: React Native: Crossplatform fast diveMobile Open Day: React Native: Crossplatform fast dive
Mobile Open Day: React Native: Crossplatform fast dive
 
MVC Design Pattern in JavaScript by ADMEC Multimedia Institute
MVC Design Pattern in JavaScript by ADMEC Multimedia InstituteMVC Design Pattern in JavaScript by ADMEC Multimedia Institute
MVC Design Pattern in JavaScript by ADMEC Multimedia Institute
 
MT_01_unittest_python.pdf
MT_01_unittest_python.pdfMT_01_unittest_python.pdf
MT_01_unittest_python.pdf
 
Angular Unit Testing NDC Minn 2018
Angular Unit Testing NDC Minn 2018Angular Unit Testing NDC Minn 2018
Angular Unit Testing NDC Minn 2018
 
D3_Tuto_GD
D3_Tuto_GDD3_Tuto_GD
D3_Tuto_GD
 
D3_Tuto_GD
D3_Tuto_GDD3_Tuto_GD
D3_Tuto_GD
 
Educate 2017: Customizing Assessments: Why extending the APIs is easier than ...
Educate 2017: Customizing Assessments: Why extending the APIs is easier than ...Educate 2017: Customizing Assessments: Why extending the APIs is easier than ...
Educate 2017: Customizing Assessments: Why extending the APIs is easier than ...
 
Un-Framework - Delivering Dynamic Experiences with HTML over the Wire
Un-Framework - Delivering Dynamic Experiences with HTML over the WireUn-Framework - Delivering Dynamic Experiences with HTML over the Wire
Un-Framework - Delivering Dynamic Experiences with HTML over the Wire
 
Beginner’s tutorial (part 2) how to integrate redux-saga in react native app
Beginner’s tutorial (part 2) how to integrate redux-saga in react native appBeginner’s tutorial (part 2) how to integrate redux-saga in react native app
Beginner’s tutorial (part 2) how to integrate redux-saga in react native app
 
How React Native, Appium and me made each other shine @ContinuousDeliveryAmst...
How React Native, Appium and me made each other shine @ContinuousDeliveryAmst...How React Native, Appium and me made each other shine @ContinuousDeliveryAmst...
How React Native, Appium and me made each other shine @ContinuousDeliveryAmst...
 
PT1420 Decision Structures in Pseudocode and Visual Basic .docx
PT1420 Decision Structures in Pseudocode and Visual Basic .docxPT1420 Decision Structures in Pseudocode and Visual Basic .docx
PT1420 Decision Structures in Pseudocode and Visual Basic .docx
 
Short Codes: Pain Free Magic
Short Codes: Pain Free MagicShort Codes: Pain Free Magic
Short Codes: Pain Free Magic
 
Learning Svelte
Learning SvelteLearning Svelte
Learning Svelte
 
Asp netmvc e03
Asp netmvc e03Asp netmvc e03
Asp netmvc e03
 
reactjs-quiz..docs.pdf
reactjs-quiz..docs.pdfreactjs-quiz..docs.pdf
reactjs-quiz..docs.pdf
 
Into React-DOM.pptx
Into React-DOM.pptxInto React-DOM.pptx
Into React-DOM.pptx
 

More from Katy Slemon

React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdfReact Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdfKaty Slemon
 
Data Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdfData Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdfKaty Slemon
 
How Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdfHow Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdfKaty Slemon
 
What’s New in Flutter 3.pdf
What’s New in Flutter 3.pdfWhat’s New in Flutter 3.pdf
What’s New in Flutter 3.pdfKaty Slemon
 
Why Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdfWhy Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdfKaty Slemon
 
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdfHow Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdfKaty Slemon
 
How to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdfHow to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdfKaty Slemon
 
How to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdfHow to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdfKaty Slemon
 
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdfSure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdfKaty Slemon
 
How to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdfHow to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdfKaty Slemon
 
IoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdfIoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdfKaty Slemon
 
Understanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdfUnderstanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdfKaty Slemon
 
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdfThe Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdfKaty Slemon
 
New Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdfNew Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdfKaty Slemon
 
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdfHow to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdfKaty Slemon
 
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdfChoose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdfKaty Slemon
 
Flutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdfFlutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdfKaty Slemon
 
Angular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdfAngular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdfKaty Slemon
 
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdfHow to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdfKaty Slemon
 
Ruby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdfRuby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdfKaty Slemon
 

More from Katy Slemon (20)

React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdfReact Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
 
Data Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdfData Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdf
 
How Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdfHow Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdf
 
What’s New in Flutter 3.pdf
What’s New in Flutter 3.pdfWhat’s New in Flutter 3.pdf
What’s New in Flutter 3.pdf
 
Why Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdfWhy Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdf
 
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdfHow Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
 
How to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdfHow to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdf
 
How to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdfHow to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdf
 
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdfSure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
 
How to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdfHow to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdf
 
IoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdfIoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdf
 
Understanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdfUnderstanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdf
 
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdfThe Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
 
New Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdfNew Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdf
 
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdfHow to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
 
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdfChoose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
 
Flutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdfFlutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdf
 
Angular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdfAngular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdf
 
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdfHow to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
 
Ruby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdfRuby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdf
 

Recently uploaded

What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?Watsoo Telematics
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningVitsRangannavar
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
buds n tech IT solutions
buds n  tech IT                solutionsbuds n  tech IT                solutions
buds n tech IT solutionsmonugehlot87
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 

Recently uploaded (20)

What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learning
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
buds n tech IT solutions
buds n  tech IT                solutionsbuds n  tech IT                solutions
buds n tech IT solutions
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 

How to develop frontend quiz app using vue js

  • 3. 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.
  • 5. Here, we will be using Vue 2. Run the below command to create the VueJs app. vue create quiz-app You’ll see something like this. Now, with the help of the following command navigate to the directory and run the server. cd quiz-add npm run serve
  • 6. The localhost will display the default screen as shown below.
  • 8. < template > containing HTML code of the component < script > containing business logic < style > containing CSS code for styling of the component Quiz component Modal component Every Vue component consists of three sections: For our demo application, we will be having two components:
  • 9. Folder Structure Here’s the image of our folder structure. It will be a pretty simple structure. Now let’s take a look at different files and see what are we going to do. Keep the note of the filename.
  • 10. In search of dedicated VueJS developers with extraordinary problem-sloving skills and VueJS expertise? Contact Bacancy: the best VueJS development company and start developing your project.
  • 12. App.vue is the parent file of all the components (here Quiz and Modal component). Let’s define our components. Refer to the following code for the UI template. <template> <div id="app"> <h2>Quiz App</h2> <quiz @quiz- completed="handleQuizCompleted" :key="quizKey" /> <custom-modal v-show="showModal" header="Congratulations!" subheader="You've completed your Quiz!" :score="score" @reload="updateQuiz" @close="showModal = false"
  • 14. v – show=” show Modal” will render the modal conditionally based on this . showmodal. The score is a dynamic prop sent to modal from data properties. The header and subheader are two static props. The reload and close are the custom events that is called from modal-footer Explanation The code is quite simple. . Moving on the < script > tag.
  • 15. <script> import CustomModal from "./components/CustomModal.vue"; import Quiz from "./components/Quiz.vue"; export default { components: { Quiz, CustomModal }, name: "App", data() { return { quizKey: 0, showModal: false, score: { allQuestions: 0, answeredQuestions: 0, correctlyAnsweredQuestions: 0, }, }; },
  • 16. methods: { handleQuizCompleted(score) { this.score = score; this.showModal = true; }, updateQuiz() { this.showModal = false; this.quizKey++; }, }, }; </script>
  • 17. 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.
  • 19. 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.
  • 20. CustomModal.vue The file CustomModal.vue will consist the UI and logic code of the modal. Refer to the code below. <template> <transition name="modal"> <div class="modal-mask"> <div class="modal-wrapper"> <div class="modal-container"> <div class="modal-header"> <h2>{{ header }}</h2> <h3>{{ subheader }}</h3> </div> <div class="modal-body"> <div id="score"> You answered <span class="highlight"> {{
  • 21. Math.floor( (score.correctlyAnsweredQuestions / score.allQuestions) * 100 ) }} % correctly! </span> Answered <span class="highlight"> {{ score.correctlyAnsweredQuestions }} out of {{ score.allQuestions }} </span> questions. </div> </div>
  • 23. <script> export default { props: { header: String, subheader: String, score: Object, }, }; </script>
  • 24. The score prop contains how many questions the user answered correctly and also contains total number of questions. We use the score prop received from the Quiz component’s custom events. The modal-footer will have two buttons emitting custom events to reload and close the modal. Explanation
  • 25. Quiz.vue <template> <div class="container"> <div class="correctAnswers"> You have <strong>{{ correctAnswers }} correct {{ pluralizeAnswer }}!</strong> </div> <div class="correctAnswers"> Currently at question {{ index + 1 }} of {{ questions.length }} </div> <h1 v-html="loading ? 'Loading...' : currentQuestion.question"></h1> <!-- Only first question is displayed -- > <form v-if="currentQuestion">
  • 27. “loading ? ‘Loading…’ : currentQuestion.question” will check the loading property and based on it will decide ‘Loading…’ or the currentQuestion. The answer of every question will be stored in the array answers. So, we will loop the answers with the help of ‘v-for’ and display every answer as the button element. With that, v-html=”answer” will display answer on the button. The logic will be executed by handleClick that we will see later in the script part. 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.
  • 28. Fetch Questions 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.
  • 29. async fetchQuestions() { this.loading = true; //fetching questions from API let response = await fetch( "https://opentdb.com/api.php? amount=5&category=21&type=multipl e" ); 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, ];
  • 30. //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; },
  • 31. Display Current Question The computed property currentQuestion() will return the current question at the current index. currentQuestion() { if (this.questions !== []) { return this.questions[this.index]; } return null; },
  • 32. Count Correct Answers 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++; } });
  • 33. return streakCounter; } else { return "--"; } },
  • 34. Calculate score 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) {
  • 35. // 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 ), };
  • 36. } else { return { allQuestions: 0, answeredQuestions: 0, correctlyAnsweredQuestions: 0, }; } },
  • 37. Watcher on Quiz Completion 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); }, },
  • 38. Check Correct Answer 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 ); }
  • 39. 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;
  • 40. /* Show right Answer */ let correctAnswer = this.questions[index].correct_answer; let allButtons = document.querySelectorAll(`[index="${inde x}"]`); allButtons.forEach(function (button) { if (button.innerHTML === correctAnswer) { button.classList.add("showRightAnswer"); } }); } } },
  • 42. 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).
  • 44. Feel free to visit the github source code: VueJS Quiz App and clone the repository to play around with the code.
  • 46. 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.