Reputation: 82903
I am trying to build a table component.
I want to define and pass the column metadata for the grid as an array prop and also pass the actual data as another prop to the grid.
I was able to achieve that without many issues.
But, now I would like to pass a dynamic component as a part of each column definition so that the user can define/control the way the cell gets rendered (content with edit delete buttons in same cell etc.)
Is there a way to pass a dynamic component as a prop and then have this component rendered?
<parent-comp>
<tr class="" v-for="result in dataSource">
<template v-for="column in columns">
<td>
<template v-if="column.customComponent">
######## How do I render this customComponent ########
</template>
</td>
</template>
</tr>
</parent-comp>
where the dataSource data can be something like
[
columns: [{
name: "something",
customComponent: SomeCustomComponent
}, {
name: "another thing",
customComponent: AnotherOtherCustomComponent
}]
]
Will be happy to elaborate/clarify on this if the ask above is not clear.
Upvotes: 11
Views: 7957
Reputation: 82459
As suggested in the comments above, you can use a dynamic component in your template and pass the definition of the component in your property.
console.clear()
const ColumnOne = {
template: `<h1>I am ColumnOne</h1>`
}
const ColumnTwo = {
template: `<h1>I am ColumnTwo</h1>`
}
Vue.component("parent-comp",{
props:["columns"],
template:`
<div>
<component v-for="column in columns"
:is="column.customComponent"
:key="column">
</component>
</div>
`
})
new Vue({
el:"#app",
data:{
columns:[{
name: "something",
customComponent: ColumnOne
}, {
name: "another thing",
customComponent: ColumnTwo
}]
}
})
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
<div id="app">
<parent-comp :columns="columns"></parent-comp>
</div>
Upvotes: 7