vue looping an object to render multiple versions of component

962 Views Asked by At

I am wanting to put multiple components in a wrapper, so it would look like this,

<div class="wrapper">
    <component />
    <component />
    <component />
</div>

I am trying the following,

<component
     v-for="person in persons"
     :key="person.key"
     :is="chooseType(person)"
     :person="person"
     :feed="person.self ? handle : aFunction(person)"
     :publisher="getPublisher(person)"
/>

My problem is that person is returning as undefined when it runs the chooseType component, why would this be, the persons object is not null, so does have children. How can I loop a dynamic component, as I assume I doing it incorrectly?

1

There are 1 best solutions below

0
On

v-for is used along with :is in dynamic component. Please find below

Vue.component('dynamic1', {
  template: '<div>Dynamic 1</div>'
})

Vue.component('dynamic2', {
  template: '<div>Dynamic 2</div>'
})

new Vue({
  el: "#app",
  data() {
    return {
      persons: [{
        name: 'dynamic1'
      }, {
        name: 'dynamic2'
      }]
    }
  },
  methods: {
    getComponent(comp) {
      return comp
    }
  }
})
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>

<div id="app">
  <component v-for="person in persons" :is="getComponent(person.name)"></component>
</div>