Reputation:
I'm making a quiz in Vue.js, quiz questions can be different types:
My problem is that types of questions are mixed (e.g. you can have any of them in the quiz) and thus are different components (<x-select-one-question>
, <x-select-multiple-question>
, <x-select-image-question>
, <x-match>
etc) so I can't simply put one component into quiz.
How can, and should I make a generic component for this? Maybe something like this?
<template>
<div>
<x-question
v-for="(question, index) in questions"
:key="index"
type="question.type"></x-question>
</div>
</template>
Upvotes: 3
Views: 5935
Reputation: 419
You can use the 'component' type then on run time set the relevante component with the attr 'is' like this:
<component :is="componentToRender(type)
In the function you will check witch component you want to return, like:
componentToRender(type){
case 'quiz1': return 'QuizOneComponent';
// continue like this
}
Upvotes: 3
Reputation: 751
Your component could be something like that
<template>
<select v-if="type == 'select'">
<option v-for="item in items" value="item.value">{{ item.text }}</option>
</select>
<select v-else-if="type == 'multiple'" multiple>
<option v-for="item in items" value="item.value">{{ item.text }}</option>
</select>
<input v-else-if="type == 'image'" type="file" id="image" name="image" accept="image/png, image/jpeg">
</template>
Vue.component('question', {
template: '#question',
props: {
type: {
default: ''
},
items: {
type: Array,
default: [
{ value: 1, text: 'One' },
{ value: 2, text: 'Two' },
{ value: 3, text: 'Three' }
]
}
}
});
With that, you should be able to pass the correct prop like 'select', 'multiple' or 'image' to show the input you want.
<div id="app">
<question type='image'></question>
</div>
Here's a fiddle if you want to try by yourself.
Upvotes: 0