Create a quiz with Vue.js
Create a quiz with Vue.js
by B L Praveen
HTML
<script src="https://jsfiddle.net/rap2h/ktcvLe0q/"></script>
<script src="https://vuejs.org/js/vue.js"></script>
<div id="app">
<h1>{{ quiz.title }}</h1>
<!-- index is used to check with current question index -->
<div class="ques_block" v-for="(question, index) in quiz.questions">
<div v-show="index === questionIndex">
<h3>{{index + 1}}) {{question.text}}</h3>
<div class="option_div" v-for="(response,resp) in question.responses">
<input type="radio" v-bind:name="index" v-bind:value="response.correct" v-model="userResponses[index]"/>
<label> {{resp | myMapping}}) {{response.text}} </label>
</div>
<!--<div class="frm_grp">
<a href="" v-on:click.prevent="submit" class="submit_answer" >Submit</a>
</div>-->
<div class="error_block hide alert alert-success">
<p>Correct</p>
</div>
<div class="error_block hide alert alert-danger">
<p>Incorrect</p>
</div>
<div class="answer_block ">
<h4>Answer Details</h4>
<p>Option {{question.responses | myCorrect}} is the correct answer</p>
</div>
<div class="extra_div">
<div class="pre_btn pull-left ">
<a href="#" v-if="questionIndex > 0" v-on:click.prevent="prev" class="prev_button"><span class="fa fa-chevron-left"></span> Previous </a>
</div>
<div class="pre_btn pull-right">
<a href="#" v-on:click.prevent="next" class="next_button">Next <span class="fa fa-chevron-right"></span></a>
</div>
</div>
</div>
</div>
<div v-show="questionIndex === quiz.questions.length">
<h2>
Quiz finished
</h2>
<p>
Total score: {{ score() }} / {{ quiz.questions.length }}
</p>
</div>
</div>
JavaScript
// Create a quiz object with a title and two questions.
// A question has one or more answer, and one or more is valid.
var quiz = {
title: 'My quiz',
questions: [
{
text: "Question 1",
responses: [
{text: 'Wrong, too bad.'},
{text: 'Right!', correct: true},
]
}, {
text: "Question 2",
responses: [
{text: 'Right answer', correct: true},
{text: 'Wrong answer'},
]
}
]
};
new Vue({
el: '#app',
data: {
quiz: quiz,
// Store current question index
questionIndex: 0,
// An array initialized with "false" values for each question
// It means: "did the user answered correctly to the question n?" "no".
userResponses: Array(quiz.questions.length).fill(false)
},
// The view will trigger these methods on click
methods: {
// Go to next question
next: function() {
this.questionIndex++;
},
// Go to previous question
prev: function() {
this.questionIndex--;
},
// Return "true" count in userResponses
score: function() {
return this.userResponses.filter(function(val) { return val }).length;
}
}
});