Search code examples
formsvue.jsvuejs2vue-componentdynamic-forms

VueJS - What's the best alternative to a long list of v-if's


I need to make a dynamic form where an admin area allows someone to add and re-arrange fields in a form. Each field has a type: date,checkbox,select,text,number etc. I've created separate components for each field type but now my form looks something like this (pseudo code to give an example).

<section v-for="field in fields">
    <field-date v-if="field.type === 'date'" v-model="field.value"></field-date>
    <field-select v-if="field.type === 'select'" v-model="field.value"></field-select>
    <field-number v-if="field.type === 'number'" v-model="field.value"></field-number>
    <field-text v-if="field.type === 'text'" v-model="field.value"></field-text>
    <field-checkbox v-if="field.type === 'checkbox'" v-model="field.value"></field-checkbox>
</section>

But this is already getting unwieldy and will only get more out of control. But I can't find a simpler way of doing this. Perhaps field should be an object with a render method? But then the if/else is just going to be abstracted elsewhere.


Solution

  • Using component.

    <section v-for="field in fields">
        <component :is="'field-' + field.type" v-model="field.value"></component>
    </section>