Is it possible to render the v-for value dynamically?

I have a dynamic component and I'm trying to iterate through different objects from it. However, my current code isn't working as intended. Can someone please guide me on how to make the activeQuestion value in v-for dynamic? Thank you for your assistance.

<component  v-for="data in activeQuestion" 
:is="data.activeComponent" 
:key="data"
:question="data.question"
:correctAnswerEnglish="data.correctAnswer">
</component>

data() {
   return {
    activeQuestion: this.test1.level1,

    test1: {
        question1: [
             {
        question: 'this is the question',
        correctAnswer: ['hello', 'world'],
        activeComponent: 'Writing',
             }
        ],

       question2: [.......]

   }
  }

Answer №1

I found a clever solution for this issue. Feel free to click on the following link to see a demo

// App.vue
<template>
    <div id="app">
        <button @click="changeQuestion">Toggle Question</button>
        <div v-if="test1[activeQuestion]">
            <component v-for="data in test1[activeQuestion]" :is="data.activeComponent" :key="data" :question="data.question" :answer="data.correctAnswer">
            </component>
        </div>
    </div>
</template>

<script>
import First from './components/First'
import Second from './components/Second'

export default {
  name: 'App',
  components: {
    First, // You can register them globally if you want
    Second
  },
  data() {
    return {
      activeQuestion: 'question1',
      test1: {}
    }
  },
 mounted() {
   callingAPI().then(data => {
    // assuming data will be in this format
    data = {
      question1: [
          {
            question: 'This is the first question',
            correctAnswer: ['hello', 'world'],
            activeComponent: 'First',
          },
          {
            question: 'This is the second question',
            correctAnswer: ['hello', 'world'],
            activeComponent: 'First',
          }
        ],
        question2: [
          {
            question: 'this is the first question',
            correctAnswer: ['test', 'test 2'],
            activeComponent: 'Second',
          },
          {
              question: 'This is the second question',
              correctAnswer: ['hello', 'world'],
              activeComponent: 'Second',
          }
        ]
    }
    this.test1 = data
   })
 },
  methods: {
    changeQuestion() {
      // Change this logic accordingly your convenience
      this.activeQuestion = this.activeQuestion === 'question1' ? 'question2' : 'question1'
    }
  }
}
</script>
// components/First.vue
<template>
    <div class="hello">
        <h1>First Component</h1>
        <h2>{{ question }}</h2>
        {{ answer }}
    </div>
</template>

<script>
    export default {
  name: 'First',
  props: {
    question: String,
    answer: String
  }
}
</script>
// ./components/Second.vue
<template>
    <div class="hello">
        <h1>Second Component</h1>
        <h2>{{ question }}</h2>
        {{ answer }}
    </div>
</template>

<script>
    export default {
  name: 'Second',
  props: {
    question: String,
    answer: String
  }
}
</script>

Answer №2

If you want to create a dynamic v-for loop in Vue, one way to do it is by using computed properties or methods. Check out this link for more information.

In the example provided in the link above, they demonstrate how to use a computed property and then iterate over it directly in the v-for loop.

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

The Angular custom modal service is malfunctioning as the component is not getting the necessary updates

As I develop a service in Angular to display components inside a modal, I have encountered an issue. After injecting the component content into the modal and adding it to the page's HTML, the functionality within the component seems to be affected. F ...

Is there a way to retrieve JSON data from a specific URL and assign it to a constant variable in a React application?

I am exploring react-table and still getting the hang of using react. Currently, in the provided code snippet, a local JSON file (MOCK_DATA.json) is being passed into the const data. I want to swap out the local JSON with data fetched from a URL. How can ...

troubleshooting problems with jquery ajax and setInterval

$(document).ready(function() { function refreshBids() { var element = $("#biddingDiv"); element.load("bids.php?id=<?=$userId;?>&init=1&auctionid=<?=$auctionId;?>"+(new Date()).getTime()); } refreshBids(); setI ...

Using Typescript to assign a new class instance to an object property

Recently, I crafted a Class that defines the properties of an element: export class ElementProperties { constructor( public value: string, public adminConsentRequired: boolean, public displayString?: string, public desc ...

There seems to be an issue with the CSS file linking properly within an Express application

Every time I run my app.js file, the index.html file is displayed. However, when I inspect the page, I notice that the CSS changes are not taking effect. Strangely, if I open the HTML file using a live server, the CSS changes are visible. Can someone exp ...

Express: router.route continues processing without sending the request

I've implemented the following code in my Express application: var express = require('express'); // Initializing Express var app = express(); // Creating our app using Express var bodyParser = require(' ...

How can I show the number of items in my filtered data using AngularJS?

My data array holds objects in JSON format. var users = { 'New':{ {Name:'One'}, {Name:'Two'} }, 'Old':{ {Name:'Three'}, {Name:'Four'} } This piece of code is used to disp ...

JavaScript - issue with event relatedTarget not functioning properly when using onClick

I encountered an issue while using event.relatedTarget for onClick events, as it gives an error, but surprisingly works fine for onMouseout. Below is the code snippet causing the problem: <html> <head> <style type="text/css"> ...

Retrieve the element that is currently being hovered over within the same nested selector

I am facing a challenge in selecting the currently hovered element with a nested selector. The ".frmElement" class is used as the selector. When I hover over the ".frmElement" element at a certain level, all the previous selector elements display the hover ...

Expanding the size of select dropdown in Material UI to accommodate more options

Is there a way to increase the width of the drop down to 400px? I tried adding inline styles, but it didn't work. Upon debugging, I realized that the width is being overridden by this class. I'm not sure how to overwrite it. Could you please prov ...

Encountering the error code 'ERR_EMPTY_RESPONSE' while utilizing an AJAX-powered live search feature

My website features a live AJAX search bar that retrieves records from a MySQL database. However, when users repeatedly conduct searches by modifying the search criteria, some web browsers display an error message stating 'ERR_EMPTY_RESPONSE'. ...

JavaScript on Ruby on Rails stops functioning in js.erb file

I have encountered an issue with pagination using AJAX in a view. Initially, I had two paginations working perfectly fine with their respective AJAX calls. However, when I tried to add a third pagination (following the same method as the previous two), it ...

The issue with Spring Boot on Heroku is that it fails to log incoming requests

While developing my Nuxt App front-end and Spring Boot API, everything functioned perfectly in my local environment. However, once I deployed both applications to Heroku, I encountered an issue where certain URLs were returning 404 error pages. Upon examin ...

Submitting an extremely large string to an Express server using JS

How can a large String be efficiently sent to a Node.js Express server? On my webpage, I am using Codemirror to load files from an Express server into the editor. However, what is the most effective method for sending "the file" (which is actually a bi ...

Encountering difficulties in updating CSS styles using the useState hook in React

I am currently working on creating a modal in react that changes the background color when opened. The goal is to have the background color darken when the modal is activated and return to normal when the modal is closed. I attempted to achieve this using ...

Using Laravel and vue.js to convert values into an array

I am currently utilizing vue.js within my Laravel project. Within the project, I have three tables: Article Location article_location (pivot table) I am looking to convert location articles into JSON format so that I can pass it to vue. How should I ...

Interactive Thumbnail Previews

There seems to be an issue with the thumbnail links on my page. The leftmost and rightmost links work fine, but the middle ones are not functioning properly when clicked. The PHP code used to generate these links is the same for all of them, so it's p ...

Utilizing Jquery to enhance table filtering functionality

I created a table listing various places, along with buttons to filter the list. The first filter is based on location (north, east, central, south, west) determined by postcode. The other filter is for "impress" which only displays places with a rating of ...

My node.js and express application is encountering an issue where it is failing with an error indicating that a variable has not been

Currently in the process of understanding how node.js and express operate. I've successfully extracted data from my mongo database... and now I'm experimenting with transferring data between my router code and views. The locations.js file within ...

Utilize jQuery to export HTML or JSON data to an Excel spreadsheet

I am looking for a way to export json or html data to an excel sheet using only html and jquery, without involving any server code. I have found some fiddles that allow me to download the excel sheet successfully, but unfortunately, none of them work in In ...