Using Vue.js to loop through data objects when a button is clicked

I'm currently working on building a quiz functionality using vue.js, but I've hit a roadblock in trying to make the "Next" button cycle through my data. The goal is to have the screen display the object containing the question and answers (e.g. questionOne, questionTwo), and then move on to the next object when the user clicks "Next". Despite my attempts in the code provided, none of them seem to be effective.

Here's the template for the Quiz Component:

<template>
  <div class="quiz-container">
    <div
      class="question-container">
      <h1> {{ currentQuestion.q }} </h1>
    </div>
    <div class="answer-container">
      <v-btn
        v-for="answer in currentQuestion.ans"
        :key="answer"
        outlined
        block
        x-large
        class="answer-btn"
      >
      {{ answer }}
      </v-btn>
    </div>
    <div
      class="navigation flex-row"
    >
      <v-btn text x-large @click="questionNav.current--">Back</v-btn>
      <v-spacer />
      <v-btn text x-large @click="qNext()">Next</v-btn>
    </div>
  </div>
</template>

And here's the script for the Quiz:

<script>
  import { mapGetters } from 'vuex';
  export default {
    name: 'quiz',
    computed: {
      ...mapGetters('user', {
        loggedIn: 'loggedIn'
      })
    },
    data() {
      return {
         curr: 0,
         currentQuestion: {
            q: 'Sample Question' ,
            ans: ['A', 'B', 'C']
         },
         questionOne: {
            q: 'How many minutes do you want to spend?' ,
            ans: ['Short (15-20)', 'Medium (20-40)', 'Long (40-60)']
         },
         questionTwo: {
            q: 'What muscle group do you want to focus on?' ,
            ans: ['Upper Body', 'Lower Body', 'Core', 'Full Body']
         },
         questionThree: {
            q: 'What level intensity do you want?' ,
            ans: ['Leisure Walking', 'Speed Walking', 'Jogging', 'Sprinting']
         },
         questionParts: [this.questionOne, this.questionTwo, this.questionThree]
      }
    },
    methods: {
      questionNav() {
         questionParts = [this.questionOne, this.questionTwo, this.questionThree]
         currentQuestion = questionParts[curr]
      },
      qNext() {
         this.currentQuestion = this.questionParts[this.curr++]
      }
    }
  }
</script>

Although I've tried implementing a "qNext" method and a "questionNav" method, they don't seem to be functioning correctly. Ideally, I would like the "Next" button to progress through [questionOne, questionTwo, questionThree]. As a beginner with vue.js, any guidance or assistance would be highly appreciated. Thank you!

Answer №1

The issue with the current setup is that you are attempting to populate the questionParts array without access to questionOne, questionTwo, and questionThree. This results in undefined values being added to the questions array.

To ensure functionality, make sure that questionParts contains the question objects. If you prefer keeping this logic within the data method, here's a revised approach:

data: () => {
  const questionOne = {
    q: 'How much time do you want to spend?' ,
    ans: ['Short (15-20)', 'Medium (20-40)', 'Long (40-60)']
  };
  const questionTwo = {
    q: 'Which muscle group do you wish to target?' ,
    ans: ['Upper Body', 'Lower Body', 'Core', 'Full Body']
  };
  const questionThree = {
    q: 'What intensity level do you desire?' ,
    ans: ['Leisure Walking', 'Speed Walking', 'Jogging', 'Sprinting']
  };
  const questionParts = [questionOne, questionTwo, questionThree]
  return {
    curr: 0,
    currentQuestion: {
      q: 'example' ,
      ans: ['1', '2', '3']
    },
    questionOne,
    questionTwo,
    questionThree,
    questionParts,
  }
},

To properly fill the questionParts array, declare necessary variables before returning from the data() function. This adjustment should enable your quiz to function correctly.

In addition, there are potential enhancements to consider such as:

  • Instead of individually declaring questionOne, questionTwo, and questionThree, you could directly create an array of questions. Based on the provided code snippet, having each question as a separate object might not be essential.
  • currentQuestion could be transformed into a computed property that retrieves the question at the specified index curr. With this modification, incrementing or decrementing curr in click handlers would automatically update the displayed question without requiring explicit assignment to currentQuestion.

Answer №2

fetchNextQuestion: function () {
        this.currentQuiz.question = this.quizParts[this.index++].question
        this.currentQuiz.answer = this.quizParts[this.index++].answer
      }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to create two separate Express sessions simultaneously?

I am encountering an issue with my Passport-using application that has a GraphQL endpoint and a /logout endpoint. Strangely, when I check request.isAuthenticated() inside the GraphQL endpoint, it returns true, but in the /logout endpoint, it returns false. ...

Exploring the contrast between 'completed' and 'upcoming' in callback functions within node.js

Within the passport documentation for authentication configuration, there is a function that appears rather intimidating as it utilizes the enigmatic function "done." passport.use(new LocalStrategy( function(username, password, done) { User.findOne( ...

What is the hierarchy for displaying elements depending on the props?

I have developed a search input component that includes an icon which I want to reposition (either on the left or right side) depending on different scenarios. This input is part of a bootstrap input-group, so modifying the order of elements within my di ...

using Angular and RxJS to filter out an element from an array

One of the functions in my service is a delete function. This function calls an API that returns either true or false. If the response is true, I then proceed to find the index of the item in my array, splice it out, and return the updated array. Here&apos ...

"Passing an Empty String as Input in a NodeJS Application

app.post('/register',function(req,res){ var user=req.body.username; var pass=req.body.password; var foundUser = new Boolean(false); for(var i=0;i<values.length;i++){ //if((JSON.stringify(values[i].usernames).toLowerCase==JSON. ...

Using JavaScript to redirect browser with a specific string

My goal is to redirect all users who visit a specific URL to another page. While this redirection works effectively, I now need to implement it with a tracking URL. The issue arises when Javascript automatically adds a "/" in front of the tracking string ...

Sending Three.js meshes to a web worker through JavaScript

I have a collection of objects, which are meshes generated using Three.js, that I need to perform operations on within a web worker. My question is, how can I send these objects to the worker? My understanding is that there's a concept called transfe ...

Consolidate two AJAX requests into a single callback

I'm developing a Chrome extension and facing the challenge of merging two separate AJAX calls into one callback upon success. What would be the most efficient approach to achieve this? Auth.prototype.updateContact = function(id, contact_obj) { var ...

Trouble maintaining router.params after page refresh

I'm experiencing a problem with vue-router. On the homepage, I have a list of posts. Whenever I click on one of them, it redirects me to the post page using this code: <router-link :to="{ name: 'article', params: {id: article.id, slug: ...

Receive AJAX aid for PHP/MySQL dynamic dropdown menu implementation

My goal is to dynamically populate a second drop-down menu based on the selection made in the first drop-down. The first drop-down contains a list of tables from my database, and the second drop-down should display providers associated with the selected ta ...

Typescript double-sided dictionary: a comprehensive guide

Looking for a dual-sided dictionary implementation in TypeScript that allows you to retrieve values using keys and vice versa. An initial approach could be storing both items as keys: dict = {"key": "value", "value": "key"} But I am curious if there are ...

Error encountered: No geographic indices found for executing a geoNear operation with Mongoose

Initially, I had divided the schemas but later nested them inside my overall document. Despite adding indexes and removing coordinates from location, there seems to be an issue with the nested points. Upon running get Indexes, it shows that there is an i ...

Is there a way to resolve the MongoDB Database-Differ Error?

I am currently working on creating an API and have set up a brand new Project, cluster, and Collection for it. However, when I attempt to use mongoose.save() to add data to my database, I keep receiving an error message. "message": { " ...

Using SCSS aliases in a Vue single file component with the help of Rollup

Adding an alias for SCSS files in a Vue SFC when using Webpack is straightforward. For example: <style lang="scss"> @import "~scss/config/config"; ... </style> This is how you would do it in Webpack: alias: { sass: path.resolve(__dirname, ...

What could be causing the browser to only partially display an image?

Have you encountered any issues with the browser not displaying an image fully? It seems like there may be a problem with the image download or rendering process, causing only part of the image to load. My application utilizes node and socket.io. Below ar ...

Experimenting with Vue Single File Components that leverage a Global Event Bus

Testing Vue components for the first time using Mocha and Webpack has been a learning experience. I followed the guidelines provided in the documentation to set up everything properly. Most of my components rely on a global event bus to communicate and em ...

Is there a way to make Express JS always serve files from the current directory no matter the route?

Currently, I am developing an Express app utilizing the Handlebars template engine. The HTML files it serves have images that direct to specific locations in my root directory. Everything works seamlessly for basic routes like "http://localhost:5000/image" ...

Select a single option from the group to include in the array

I'm currently developing a new soccer betting application. My goal is to allow users to choose the result of a match - whether it's a win, loss, or draw - and then save that selection in a list of chosen bets. https://i.stack.imgur.com/hO3uV.png ...

What is the process for creating unit tests for a method that utilizes the @Transaction() decorator?

I am currently using NestJS 6 and TypeORM to interact with a MySQL database. While attempting to write unit tests for a method that utilizes the @Transaction() and @TransactionManager() decorators, I encountered the following error message: ConnectionNotF ...

Automatically Dismissing a Bootstrap Alert After a Set Number of Seconds

Having some trouble closing a Bootstrap alert automatically on my new site built using the Bootstrap Framework. The issue arises when trying to close the alert after a certain amount of time. On the main page of the site, there is a modal login form. When ...