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 PDF file cannot be displayed due to the dynamic loading of the path and filename

Currently, I am working on an AngularJS and Java application. The following HTML code is utilized to open a PDF file in the browser. However, there seems to be an issue where the PDF does not open when dynamically passing the value for the data attribute. ...

Customize the drawer background in Vue Material

Recently, I developed a vuejs application incorporating Google's material design components. I've been exploring options to customize the background color. <template> <div class="page-container"> <md-app> ...

Upon the initial rendering, Next.js obtains access to the query { amp: undefined }

When using Next.js 9.3, I encountered an issue where I needed to access the query on initial render and pass the result of the query to next/head in order to change the title and description of the page. The component is receiving the query from the useRo ...

Grabbing nested JSON Array data using Node.js

As a beginner in Node.js, Iā€™m attempting to extract data from the JSON below: var data1 = { "_id":"R1::table::A1::order::167::comanda::2", "_rev":"1-ed6df32d3b4df9cc8019e38d655a86f5", "comanda":[ [ { ...

Showing the contents of an array which contains arrays

Retrieves the elements stored in the history array. Each element of the history array is a separate array containing fields with names and values. The goal is to display this history table by iterating over each element of the array and displaying it in ...

What is the best way to share models across different node.js projects?

In my setup, I have two node.js projects - project A and project B. Project A serves as the main project, while project B is more of an "ad-hoc" project with a specific purpose. The challenge lies in the fact that project B requires access to project A&apo ...

Bokeh is having trouble loading from the CDN

I am currently attempting to embed a plot along with its data by utilizing autoload_static within a straightforward html page that I wish to view locally on my computer. According to the documentation, all I need to do is place the .js file in the specifie ...

Calculate the difference and sum of time values with varying signs in JavaScript

-12:00 - 5:30 => -6:30 -2:00 - 5:30 => 3:30 00:00 - 5:30 => -5:30 6:00 - 2:30 => 3:30 I am interested in subtracting time with both positive and negative indices. let myCountries = [ { countryName: "NewZealand", ...

What could be the reason for webpack not making jQuery available as a global variable?

For my current project, I am utilizing several npm modules by integrating them using yarn and webpack. These essential modules include jquery, bootstrap3, moment, jquery-tablesort, jquery-ujs, bootstrap-select, and livestamp. Some of these plugins require ...

Excess space noted at the bottom of tablet and mobile versions of the page

I'm struggling to troubleshoot an issue with the mobile and tablet versions of a web-shop I'm designing for university. Some pages have excessive space after the HTML tag, but only on certain pages. I've tried commenting out CSS lines relate ...

A Vue.js trick to modify the element's class within a v-for loop when hovering in and out

I'm having trouble changing the class of a single element within a v-for loop based on mouseenter/mouseleave events. I want only the hovered element to change its class, but currently, all elements in the list are affected. I attempted binding the cl ...

Switch up the CSS variable within an embedded iframe

I'm in a predicament with a specific issue. I am currently utilizing Angular to incorporate an Iframe. Let's imagine the angular app as A and the Iframe as B. B is being loaded within A. Within B, I have utilized CSS variables to define colors. I ...

Is there a way to dynamically import a JSON file within an ECMAScript module?

Currently, I am attempting the following in my code: let filePath = '../../data/my-file.json' import inputArray from filePath assert { type: 'json' } The outcome of this operation is as follows: file:///.../script.mjs:5 import inputArr ...

Having issues with the onclick _dopostback function in MVC? It seems like the post

When attempting to execute a postback in ASP.NET MVC after confirming with JavaScript, the following button is used: <input type="submit" id ="RemoveStatus" value="Remove Status" name="button" onclick="return CheckRemove();"/> The JavaScript code f ...

Is there a way to modify the edit button to become a save button and include a cancel button?

Is there a way to toggle between an edit button and a save button, along with a cancel option? $('#edit').click(function() { $(this).hide(); $('#save, #cancel').show(); }); $('#cancel').click(function() { $('#ed ...

What is the best way to transfer Kendo Grid row data to a Kendo popup window within a partial view using jQuery?

I am currently facing a challenge in passing the row data from the Kendo Grid to a partial view that is displayed through a Kendo popup window. Within the partial view, users have the option to upload an image file related to the specific row record. This ...

Conceal any child elements that are cut off as a result of the overflow hidden property

Despite the numerous questions on this topic, none provide a suitable answer. In this scenario, the overflow hidden property is applied to the parent div. The goal is to display only the child elements that are fully visible within this container. In the ...

Having trouble with integrating Firebase and Vue database

While attempting to integrate Firebase with my Vue 4 application, I encountered the following error: Uncaught TypeError: db__WEBPACK_IMPORTED_MODULE_1_.default.database is not a function The versions I am using are: "firebase": "^9.0.0&qu ...

Issue with React Native and Redux: Prop values are updating without being called

I'm currently facing a problem with React Native and Redux integration. Using a Redux state to toggle a modal visibility between components seems like the most efficient solution due to its cross-component nature. The modal opens and closes as expec ...

Stripping double quotes from json output

Using a basic array to reference icons like so: {name: "text", avatar: srcs[15]} has been working perfectly. However, I am now dynamically creating an array from my JSON API, resulting in an array of objects structured like this: {name: "text", avatar: ...