Write less VueJS Code using the <component /> component

I finished the recommendation system, and it had 49 levels of nested if's

So sayeth Adam (a friend) and that was how he to be known as "The Lord of Nested if's". To bring this into perspective, Imagine the following code

if a_condition_is_met: # level 1
    if another_condition_is_met: # level 2
        if yet_another_condition_is_met: #level 3
            #... down to level 49
    elif a_second_condition_is_met: # level 2 branch 2
        # ... so it continues with deep nesting and branching

Now, that was long ago and he writes much neater code today, but I want to address all the "if disciples" out there.

I was refactoring a codebase which constructs HTML forms based on JSON data which makes the forms to easily be modified and shared with other users. But alas, it had an if entanglement 😅. Let me show you

 <b-select if="field.type === 'select'"
           :required="field.required"
           v-model="shadowValue"
           :mode="field.mode"
           @change="$emit('input', shadowValue)"
           :readOnly="field.read_only"
           :options="field.options" />

<!--
a bunch of other v-else-if's to render image  upload fields, 
checkboxes, radio, etc.
-->
 <b-input v-else
          :placeholder="field.label"
          :type="field.type"
          :multiline="field.multiline" # regular input field or textarea
          :required="field.required"
          :readOnly="field.readonly"
          :min="field.min"
          :max="field.max"
          v-model="shadowValue"
          @input="$emit('input', shadowValue)" />

<!-- 
field JSON representation
{
    "type": "date",
    "label": "Date",
    "size": {
        "span": 8
    }
}
-->

The form scope originally only included a few input types, until the project grew and we had some 16+ conditional matching and we still had new field types to be added. There are no nested ifs, but there there are a lot of ifs.

And this is where we got to use the vue <component/> tag. We had lesser if's, shorter code and our code came to look like

<component :is="field.tag" v-bind="field"
            @input="$emit('input', shadowValue)" />

<!-- 
field JSON representation
{
    "tag": "b-input",
    "type": "date",
    "label": "Date",
    "size": {
        "span": 8
    }
}
-->

This meant we could use all input field types provided by our component library and even our own custom components without having to explicitly add a new v-if block.

Do you think that's clean code? Let me know in the comments.

No Comments Yet