How to Build a Quiz App with Vue.js and Firebase

In this tutorial, we will learn how to build a quiz app using Vue.js and Firebase. We will use Firebase as our backend to store our quiz questions and answers, and Vue.js to build the user interface and handle the front-end logic.

Prerequisites

To follow along with this tutorial, you will need to have the following installed on your machine:

  • Node.js
  • Vue CLI
  • Firebase account

Setup Firebase Project

  1. Log in to your Firebase account and create a new project.
  2. Go to the project settings and click on the “Add Firebase to your web app” button. Copy the config object.
  3. Create a new file named .env.local in the root directory of your project.
  4. Add the following line to the .env.local file, replacing the placeholders with your Firebase project config values:
VUE_APP_FIREBASE_CONFIG=YOUR_FIREBASE_PROJECT_CONFIG

Create Vue.js App

  1. Open your terminal and navigate to the directory where you want to create your Vue.js app.
  2. Run the following command to create a new Vue.js project:
vue create quiz-app
  1. Select the default preset and wait for the app to be created.
  2. Navigate to the project directory:
cd quiz-app
  1. Install the dotenv package to load the .env.local file:
npm install dotenv
  1. Open the main.js file and add the following code at the top:
import dotenv from 'dotenv'

dotenv.config()
  1. Run the app to make sure everything is set up correctly:
npm run serve

You should see the default Vue.js app running at `http://localhost:8080`.

Configure Firebase in Vue.js

  1. Install the Firebase dependencies:
npm install [email protected]
  1. Create a new file named firebase.js in the src directory.
  2. Add the following code to the firebase.js file:
import { initializeApp } from 'firebase/app'
import { getFirestore } from 'firebase/firestore'

const firebaseConfig = JSON.parse(process.env.VUE_APP_FIREBASE_CONFIG)

// Initialize Firebase app
const app = initializeApp(firebaseConfig)

// Get Firestore instance
const db = getFirestore(app)

export default db
  1. Open the main.js file and import the firebase.js file at the top:
import './firebase'
  1. Now, Firebase is configured and ready to be used in the app.

Create Quiz Component

  1. Create a new file named Quiz.vue in the src/components directory.
  2. Add the following code to the Quiz.vue file:
<template>
  <div class="quiz">
    <h2>{{ currentQuestion.question }}</h2>
    <ul>
      <li v-for="option in currentQuestion.options" :key="option">
        <input type="radio" name="answer" :value="option" v-model="selectedAnswer">
        {{ option }}
      </li>
    </ul>
    <button @click="checkAnswer">Next</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      currentQuestion: {},
      selectedAnswer: null
    }
  },
  methods: {
    checkAnswer() {
      // TODO: Check the selected answer
    }
  }
}
</script>

<style scoped>
.quiz {
  text-align: center;
}
</style>
  1. Import the Quiz.vue component in the App.vue file and add it to the template:
<template>
  <div id="app">
    <h1>Quiz App</h1>
    <Quiz></Quiz>
  </div>
</template>

<script>
import Quiz from './components/Quiz'

export default {
  components: {
    Quiz
  }
}
</script>

<style>
#app {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}
</style>
  1. Run the app to make sure the Quiz component is rendered correctly:
npm run serve

You should see the “Quiz App” heading and the quiz component on the page.

Fetch Quiz Questions from Firebase

  1. Open the Quiz.vue file and import the db instance from the firebase.js file at the top:
import db from '../firebase'
  1. Add the following created lifecycle hook to fetch the quiz questions from Firebase:
<template>
  <!-- ... -->
</template>

<script>
export default {
  data() {
    return {
      currentQuestion: {},
      selectedAnswer: null
    }
  },
  created() {
    this.fetchQuestions()
  },
  methods: {
    async fetchQuestions() {
      const questionsCollection = collection(db, 'questions')
      const questionsSnapshot = await getDocs(questionsCollection)
      questionsSnapshot.forEach((doc) => {
        this.currentQuestion = doc.data()
      })
    },
    checkAnswer() {
      // TODO: Check the selected answer
    }
  }
}
</script>

<style scoped>
<!-- ... -->
</style>
  1. Run the app and make sure the quiz questions are fetched correctly:
npm run serve

Show Quiz Questions and Check Answers

  1. Update the Quiz.vue template to display the quiz questions and check the selected answer:
<template>
  <div class="quiz">
    <h2>{{ currentQuestion.question }}</h2>
    <ul>
      <li v-for="option in currentQuestion.options" :key="option">
        <input type="radio" name="answer" :value="option" v-model="selectedAnswer">
        {{ option }}
      </li>
    </ul>
    <button @click="checkAnswer">Next</button>
  </div>
</template>
  1. Update the checkAnswer method to check the selected answer:
<script>
export default {
  data() {
    return {
      currentQuestion: {},
      selectedAnswer: null
    }
  },
  created() {
    this.fetchQuestions()
  },
  methods: {
    async fetchQuestions() {
      // ...
    },
    checkAnswer() {
      if (this.selectedAnswer === this.currentQuestion.answer) {
        alert('Correct answer!')
      } else {
        alert('Wrong answer, try again!')
      }
      this.selectedAnswer = null
    }
  }
}
</script>
  1. Run the app and test the quiz by selecting answers and clicking the “Next” button:
npm run serve

Conclusion

In this tutorial, we learned how to build a quiz app using Vue.js and Firebase. We set up Firebase as our backend to store the quiz questions and answers, and used Vue.js to build the user interface and handle the front-end logic. We fetched the quiz questions from Firebase and displayed them to the user. We also implemented the logic to check the selected answer and provide feedback to the user. You can take this app further by adding more quiz questions, implementing a scoring system, and adding a leaderboard to track the user’s progress. Happy coding!

Related Post