9

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 $mount 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 <component> 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?

2 Answers 2

15

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: https://jsfiddle.net/f5n5z5oo/2/

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!

Sign up to request clarification or add additional context in comments.

1 Comment

As always is much easier than what I though :) thanks for the hint on v-for with this I also have access to the $index and solve my oncoming next problem, awesome. This is how my fiddle looks like now, with data and props, using the $index value jsfiddle.net/f5n5z5oo/3 thanks again
5

Hope this helps someone in future : There are numerous methods of doing this , below is one way of doing this :

1. If component is already defined , simply adding a new instance of component importantly using parent keyword to define parent of component instance as below : check codepen

var Child = Vue.extend({
    template: '<div>Hello!</div>',
});

new Vue({
  el: '#demo',
  ready: function() {
    var child = new Child({
        el: this.$el.querySelector('.child-host'),
        parent: this,
    });
  },
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.