I would like to use v-for
to render list of components from the list I have in data.
This is my code
<template>
<ticket-panel/>
<user-panel/>
<map-panel/>
<info-panel/>
<product-panel/>
</template>
I want to do something like this
<template v-for="component in components" :key="name">
??? <component> ???
</template>
data: function() {
return {
components: [
{ name: "ticket-panel" },
{ name: "user-panel" },
{ name: "map-panel" },
{ name: "info-panel" },
{ name: "product-panel" }
]
}
}
How to write <template>
or <componentName>
so it renders properly? I used Google a lot but I did not find any close answer.
CodePudding user response:
you can try like following snippet, with special attribute :is
const app = Vue.createApp({
data() {
return {
components: [{name: "ticket-panel"}, {name: "user-panel"}, {name: "map-panel"}, {name: "info-panel"}, {name: "product-panel"}]
};
},
})
app.component('ticket-panel', {
template: `<div>ticket-panel</div>`
})
app.component('user-panel', {
template: `<div>user-panel</div>`
})
app.component('map-panel', {
template: `<div>map-panel</div>`
})
app.component('info-panel', {
template: `<div>info-panel</div>`
})
app.component('product-panel', {
template: `<div>product-panel</div>`
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
<div v-for="component in components" :key="component.name">
<component :is="component.name"></component>
</div>
</div>
CodePudding user response:
You can try this process, hopefully, it will work for you. Here is an example for you:
var example1 = new Vue({
el: '#example-1',
data: {
items: [
{ message: 'Foo' },
{ message: 'Bar' }
]
}
})
<ul id="example-1">
<li v-for="item in items" :key="item.message">
{{ item.message }}
</li>
</ul>