Search code examples
vue.jscomponents

Can I variably choose what Vue.js component to use in a template?


Let's say I have a list of objects, like this:

[
  {
    "component": "component-a",
    "data": { "x": 42 }
  },
  {
    "component": "component-b",
    "data": { "state": "New York" }
  }
]

I am looping through that list, like this:

<div v-for="item in items">
  // ...
</div>

I want to choose what component to use based on item.component in each iteration. Is there a way to get Vue.js to render the following?

<div>
  <component-a data="{x:'a'}"></component-a>
</div>
<div>
  <component-b data="{state:'New York'}"></component-b>
</div>

Solution

  • you are looking for dynamic components

    <div v-for="item in items">
      <component v-bind:is="item.component" data="item.data"></component>
    </div>