Yerko Palma Yerko Palma - 5 months ago 249
Javascript Question

How to add dynamic components/partials in Vue.js

I need to add child components dynamically to a component based on user interaction. I looked to some old issue but it seems like a dirty hack to me, besides, it is an old issue, and vue development is really active, so I don't know if there is some better approach now.

What I've tried so far is here on this fiddle but is obviously not working, it says that

can only be called once. I don't know how to do it, my other option would be dynamic component, but for that I would also have to add a
element dynamically so it turns to be almost the same issue.

So how could I add a component on client click or other client event?


You want to put the custom components there right from the start, and use v-if or v-for to show, hide, add, or subtract these components. You let the data drive the DOM, not managing the DOM yourself. Fiddle example:

You can even make the components dynamically change what type of component they are using is:

data: {
  elements: [
    { type: 'component-a' },
    { type: 'component-b' }
<div v-for="element in elements" :is="element.type"></div>

If you're more specific about your use case I will try to help further!