Dynamic Components with Props, Events, Slots and Keep Alive

Dynamic Components are simple but very powerful.

Take a look at this pen I put together to see some different ways in which they can be used.

Read through the comments carefully.

See the Pen Vue.js Dynamic Components with Props, Events, Slots and Keep Alive by Patrick O’Dacre (@patrickodacre) on CodePen.

Be Careful Not to Make a Mess

If each child component is going to work with a different set of data, the <component :is="currentComponent"... /> can get very cluttered with different properties and event handlers: <component :is="currentComponent" :child1Data="" :child2Data="" :child3Data="" v-on:eventOne="" v-on:eventTwo="" v-on:eventThree=""></component> etc…

Here are some possible ways to keep things clean:

  • each child component can work with a generic prop like I did with parentData in my example.
  • any child component can emit the same generic event.

Of course, needs may be so different from child to child that it doesn’t make sense to use generic props or events. Just keep the above in mind and use your best judgment, as things can get very complicated if you let them get out of hand.

Possible Use Cases

In one project, I put a dynamic component in a Google Material Drawer component (aka ‘Off-canvas panel’ or ‘rollover’).

This allowed me to reuse the Drawer and load different components in it depending on the situation.

  • Click Create Customer Button — I loaded the Create Customer Form as the dynamic component in the Drawer.
  • Click Filter Customer List — I loaded the Filter Options Form as the dynamic component in the Drawer.

In each case, I used the same Drawer component. It was only the component inside that changed.

Combined with the <keep-alive> component to keep form data intact, it was a great setup.

How will you use Dynamic Components?

I really like this feature of Vue.js, and I’m curious to know how others are using it. Please let me know in the comments below!

Found this helpful?

If this short post has helped you in any way, please leave a comment below and remember to give this a recommendation.

Comments, questions and constructive feedback are always welcome.

My name is Patrick O’Dacre, and I’m a software developer currently available for new opportunities.

It has been my pleasure to create ground-breaking e-commerce order systems, beautiful sales dashboards, and complex data grids with some incredibly talented people that made sure work never felt like work.

Some of my favorite tools include Vue.js, React.js, Node.js and Laravel, and I’m always excited to learn new things.

I love building great things with great people. Let’s build something great together.