Learn Quickly: 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.

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 chief builder at BuildtoLearn.io — a place where growing developers can get more comfortable with full stack development by helping aspiring entrepreneurs build application prototypes.

If you’re interested in full stack JavaScript development and getting more experience with taking a full application from Zero to Production, visit BuildtoLearn.io and sign up for updates.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.