2

I'm using Vue.js to build ui for my html5 game. I have a case where I want to define ui-containers which essentially just group other ui-components and position them to somewhere on screen. So I could have something like this going on:

<ui-container>
  <ui-component1></ui-component1>
  <ui-component2></ui-component2>
  <ui-component3></ui-component3>
</ui-container>

Where I need to add and remove those components dynamically based on data-model which represents the content of the container. The problem is that I'd like to keep ui-container generic, so that I can append any Vue-component to it without having information in template about which components there might be.

I googled and found this example which concerns injecting components dynamically: http://forum.vuejs.org/topic/349/injecting-components-to-the-dom While the data-driven version in example was easy to make and understand, it uses v-for for tag and therefore requires one to know before hand the type of child-component.

So question is, how I can generalize that example to work with any component dynamically? Should my data-model have the type of component or tag name of it and then interpolate it in v-for? Or is there existing mechanism for this kind of requirement?

Tumetsu
  • 1,661
  • 2
  • 17
  • 29

1 Answers1

2

You can use special is attribute to dynamically set the type of a component. Here are the docs. The code will look somewhat like:

<div id="app">
  <div v-for="component in components" :is="component.type" :value="component.value"></div>
</div>

Working fiddle to play with: Dynamic Vue.js components

pkawiak
  • 1,329
  • 12
  • 11