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>