将Vue组件添加到DOM

pjngdqdw  于 7个月前  发布在  Vue.js
关注(0)|答案(2)|浏览(81)

我想动态地将Vue组件添加到容器中。
我有一个Dashboard.vue这样的:

<template>
   <div id="container"></div>
</template>

字符串
有三个分量:LineChart.vue , Bar.vue , Cake.vue
我将根据用户想要搜索的内容从数据库中获取数据,每次他们进行查询时,我都希望将3个组件中的一个添加到"container"
例如,如果用户进行了4次查询,生成了2个折线图,1个条形图和1个蛋糕,我希望Dashboard.vue看起来像这样:

<template>
   <div id="container">
      <LineChart id="lineChart1"></LineChart>
      <LineChart id="lineChart2"></LineChart>
      <Bar id="bar1"></Bar>
      <Cake id="cake1"></Cake>
   </div>
</template>

ymzxtsji

ymzxtsji1#

你可以使用vuejs动态组件。假设你的后端返回这个结果,其中component是你的vue组件的名称:

items = [
     {component:"LineChart", ...},
     {component:"LineChart", ...},
     {component:"Bar", ...},
     {component:"Cake", ...},
]

字符串
你的HTML模板应该看起来像这样:

<template>
   <div id="container">
      <template v-for="(item,index) in items" >
          <component :key="index" :is="item.component" :id="`${item.component}${index}`"></component>
      </template>
   </div>
</template>

8xiog9wr

8xiog9wr2#

我能想到的最简单的方法是为每个组件创建一个v-for
你会得到这样的东西:

<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>

字符串
但是,我真的相信,有一个更好的方法。

相关问题