【发布时间】:2018-11-12 00:46:04
【问题描述】:
我有三个模板。 AddCard.vue 、 ImageCard.vue 和 VideoCard.vue
AddCard.vue 上面有两个按钮,一个是添加图像卡,另一个是添加视频卡。我需要根据按钮单击添加组件。这是三个模板和我的 index.html 文件。
index.html
<!doctype html>
<html lang="en">
<head>
</head>
<body>
<div id="app">
<div class="container">
<div id="dynamic_components">
<!-- add components here -->
</div>
<addcard></addcard>
</div>
</div>
<script src="{{ asset('js/app.js') }}"></script>
</body>
</html>
AddCard.vue
<template>
<div class="buttons">
ul class="no-margin-list">
<li @click="imagecard">
<span class="card_icon">
<img :src="'img/image.jpg'" >
</span>
<p>Add Image Card</p>
</a>
</li>
<li @click="videocard">
<span class="card_icon">
<img :src="'img/video.jpg'" >
</span>
<p>Add Video Card</p>
</a>
</li>
</div>
</template>
<script>
export default {
computed: {
},
methods: {
imagecard(val) {
//how to add image card
},
videocard() {
//how to add video card
}
},
}
</script>
ImageCard.vue
<template>
<h1> I am a image Card </h1>
</template>
<script>
</script>
VideoCard.vue
<template>
<h1> I am a Video Card </h1>
</template>
<script>
</script>
我需要在 <div id="dynamic_components"> 中一个接一个地动态添加组件。用户可以添加任意数量的卡片。
如何动态添加组件。请指点我一个教程。
【问题讨论】:
-
牢记数据驱动。对于您的情况,将一个数组定义为 data/computed property=cards,例如
[{'card-content':{}, 'card-type':'image'}, {'card-content':{}, 'card-type':'image'}],然后在您的模板中,<div> <!-- add components here --><template v-for="(card, index) in cards" :key="index" :is="card['card-type']"></template> </div> -
@Sphinx ,所以每次用户单击按钮时,我都需要在计算属性中推送新的数组元素,v-for 将负责在 UI 上呈现它。
-
@Sphinx 请写一个答案,您刚刚提供了一个很好的答案,但作为评论......
标签: vue.js