Skip to content Skip to sidebar Skip to footer

Generic Components In Vue

I'm making a quiz in Vue.js, quiz questions can be different types: Select one Select multiple Select image Match My problem is that types of questions are mixed (e.g. you can ha

Solution 1:

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
}

Solution 2:

Your component could be something like that

<template>
<selectv-if="type == 'select'"><optionv-for="item in items"value="item.value">{{ item.text }}</option></select><selectv-else-if="type == 'multiple'"multiple><optionv-for="item in items"value="item.value">{{ item.text }}</option></select><inputv-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.

Post a Comment for "Generic Components In Vue"