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

"Animating a card to slide in from the left side upon clicking a button in a React app

How can we create a feature where, upon clicking "Apply Coupon" in Image 1, a window slides in from the left just above the webpage (as shown in Image 2)? Additionally, in Image 2, there is a blue transparent color on the webpage adjacent to this sliding w ...

Customizing jQuery dialog: What is the best way to change the appearance of the close button?

I am struggling to style the close tag in my jQuery dialog box. I have looked through the documentation and tried various CSS alterations, but nothing seems to be working. Any suggestions or insights would be greatly appreciated. My code is provided below ...

Applying a variety of elements to a single function

I am in the process of creating a mini-survey and I want the buttons to change color when clicked, but return to normal when another button is selected within the same question. Currently, clicking on a button turns it red while leaving the others clear. H ...

What is the appropriate way to utilize `render_template` from Flask within Angular?

I'm facing an issue where I need to implement different routes for various Angular Material tabs. I have attempted to directly call Flask from the template, as demonstrated below, but unfortunately, I am unable to invoke render_template from Angular. ...

Javascript chart

Hello everyone, I am diving into the world of fetch API. Currently, I am faced with a challenge where I need to generate the following list items: <li>Zimmerman, Paul</li> <li>Yimmerman, Raul</li> <li>Limmerman, Caul</li> ...

How can I continuously trigger the expand transition of a v-card by pressing a button?

I'm currently working on a form where users can click a button to reveal a new v-card. While everything is functioning properly, I am having trouble implementing a smooth expand transition. The transition works for the first card, but then prompts me ...

Typescript Routing Issue - This call does not match any overloads

Need assistance with redirecting to a sign-up page upon button click. Currently encountering a 'no overload matches this call' error in TypeScript. Have tried researching the issue online, but it's quite broad, and being new to Typescript ma ...

Encountered a RunTime Error when attempting to Lazy Load a module

When attempting to lazy-load a component separately, an unexpected run-time error is occurring. This issue is specifically related to writing loadChildren within the routing module of another component in Angular 6. Any assistance with resolving this error ...

Ways to retrieve the page name where the script originates from

I have a function that is triggered from three different pages. Each page involves adding an attribute to a specific div. For instance: <div id="posts" page="home"></div> <div id="posts" page="feed"></div> <div id="posts" page= ...

empty responseText from GET request using AJAX

I've been working on a chatbox using AJAX and I've encountered an issue where my xhttp.responseText is coming back empty. In firebug, I can see that the GET request is being sent and the correct text is being returned, but for some reason it&apos ...

Verify login availability using Javascript auto-check

For quite some time now, I've been grappling with a significant issue that has been consuming my attention. I am determined to implement an auto-check login availability feature in the registration form of my website. My goal is for it to verify the ...

Is it possible to execute TypeScript class methods in asynchronous mode without causing the main thread to be blocked?

Creating an app that retrieves attachments from specific messages in my Outlook mail and stores the data in MongoDB. The challenge lies in the time-consuming process of receiving these attachments. To address this, I aim to execute the task in a separate t ...

Determining the specific condition that failed in a series of condition checks within a TypeScript script

I am currently trying to determine which specific condition has failed in a set of multiple conditions. If one does fail, I want to identify it. What would be the best solution for achieving this? Here is the code snippet that I am using: const multiCondi ...

To include a Material Icon in your React-Toastify notification

This is an example of code located in a specific folder. While trying to incorporate a material Icon, an error has been encountered. 'React' must be in scope when using JSX import { toast } from 'react-toastify'; import ErrorIcon from ...

What is the best method for applying an active class to a particular element?

I have the following methods: methods: { replyBox: function(event){ event.preventDefault(); this.isActive = !this.isActive; ); }, In my view, I have this: <div class="comment_list" v-for="comme ...

Steps for including a subdocument within a mongoose schema

I am currently working on setting up a subdocument within a mongoose schema using node.js/Express. There are two schemas in play: Member and Address Member.js // app/models/member.js // Loading mongoose to define the model var mongoose = require(' ...

(Is it even necessary to use a timezone library for this straightforward scenario?)

As I delve into the realm of time zones for the first time, I've heard tales of how challenging it can be for developers. To ensure I am on the right track, I am posing this question as a safeguard to make sure nothing is overlooked. My scenario is q ...

Converting JavaScript numbers into years and months format

Given an integer, for example 20, I am trying to calculate how many months and years are represented by that number. For 20, the result would be 1 year and 8 months. How can this be achieved using JavaScript? switch (props.term) { case (props.term ...

Modules failing to load in the System JS framework

Encountering a puzzling issue with System JS while experimenting with Angular 2. Initially, everything runs smoothly, but at random times, System JS struggles to locate modules... An error message pops up: GET http://localhost:9000/angular2/platform/bro ...

Node.js socket.io emit function not functioning properly

In my current configuration, I have the following setup: app.set('port', process.env.PORT || 3000); var httpserver = http.createServer(app).listen(app.get('port'), function(){ console.log('Express server listening on port ' ...