I would like to dynamically append Vue Components to a container.
I have a Dashboard.vue
like this:
<template>
<div id="container"></div>
</template>
Then I have 3 components: LineChart.vue , Bar.vue , Cake.vue
I will be fetching data from a database depending on what users want to search, and everytime they make a query, I want to append one of the 3 components into "container"
So for example if a user makes 4 querys, generating 2 LineCharts, 1 Bar and 1 Cake, I want the Dashboard.vue
to look like this:
<template>
<div id="container">
<LineChart id="lineChart1"></LineChart>
<LineChart id="lineChart2"></LineChart>
<Bar id="bar1"></Bar>
<Cake id="cake1"></Cake>
</div>
</template>
CodePudding user response:
You can use vuejs dynamic components. Let's say that your backend returns this result, where component is the name of your vue component :
items = [
{component:"LineChart", ...},
{component:"LineChart", ...},
{component:"Bar", ...},
{component:"Cake", ...},
]
Your html template should look like :
<template>
<div id="container">
<template v-for="(item,index) in items" >
<component :key="iindex" :is="item.component" :id="`${item.component}${index}`"></component>
</template>
</div>
</template>
CodePudding user response:
The easiest way I can think of for this is to make a v-for
for each component.
You will have something like this:
<template>
<LineChart v-for="i in lineCount" :key="'line' i" />
<Bar v-for="i in barCount" :key="'bar' i" />
<Cake v-for="i in cakeCount" :key="'cake' i" />
</template>
However, I am really sure though, there is a better approach for this.