Vue.js Dynamic Components for Polymorphism

Polymorphism is the ability of an object to take on many forms.

Vue.js provides an easy way to use dynamic components in our app:

<component is=”h1" > Hola </component>

In the snippet above we are rendering an <h1>, lets render a dynamic component:

<component :is=”selectedCmp” />

The selectedCmp is a variable holding the desired component name.

The need for a common API

If we want to dynamically switch between components, they should have a similar API, for example:

<component :is=”selectedCmp“
:info=“someInfo“
@inform=“doSomething”
/>

We are passing down a prop called info and expecting an event named inform.

Dynamic components are a shape of Polymorphism -
We use different components with similar API.

Let us build a dynamic survey:

var survey = {
title: ‘Robots Shopping’,
cmps: [
{
type: ‘textBox’,
info: {
label: ‘Your name:’
}
},
{
type: ‘selectBox’,
info: {
label: ‘How was it:’,
opts: [‘Great’, ‘Fine’, ‘Crap’]
}
},
{
type: ‘linearScale’,
info: {
label: ‘Quality:’,
max: 5
}
},
]
}

We can build a form that contains components based on the cmps array:

<form @submit.prevent="save">
   <div v-for="(cmp, idx) in survey.cmps">
      <component :is="cmp.type"
:info="cmp.info"
@setVal="setAns($event, idx)">
</component>
   </div>
   <button>Save</button>
</form>

Lets consider the text-box component:

Note that it also includes a <datalist> to suggest some options to the user:

Note: In the example above, to keep the datalist id unique, I am using Vuejs component id in a computed property.

Here is a link to a live demo and to the repo, enjoy!

Summary

With dynamic components we can build generics apps, 
I call them: meta-applications, here are some more examples:

Google Keep Replica (See it in action here)

Each note is represented by a component

2. Site builders (such as WIX) see it in action here.

Code away!