vue实现添加卡片
Vue 实现添加卡片功能
数据驱动渲染
在Vue中,卡片通常通过v-for循环数据数组渲染。定义cards数组存储卡片数据,每个卡片对象包含标题、内容等属性:
data() {
return {
cards: [
{ id: 1, title: '卡片1', content: '内容示例' },
{ id: 2, title: '卡片2', content: '内容示例' }
]
}
}
模板渲染
使用v-for绑定cards数组到模板,动态生成卡片元素:

<div class="card-container">
<div v-for="card in cards" :key="card.id" class="card">
<h3>{{ card.title }}</h3>
<p>{{ card.content }}</p>
</div>
</div>
添加卡片方法
通过方法向数组添加新卡片数据,触发视图自动更新:
methods: {
addCard() {
const newId = this.cards.length + 1
this.cards.push({
id: newId,
title: `卡片${newId}`,
content: '新卡片内容'
})
}
}
触发添加操作
绑定按钮点击事件调用addCard方法:

<button @click="addCard">添加卡片</button>
样式优化
添加基础CSS使卡片可视化更清晰:
.card-container {
display: flex;
flex-wrap: wrap;
gap: 16px;
}
.card {
border: 1px solid #ddd;
border-radius: 8px;
padding: 16px;
width: 200px;
}
表单动态输入
进阶实现可通过表单动态输入卡片内容:
<input v-model="newCard.title" placeholder="标题">
<textarea v-model="newCard.content"></textarea>
<button @click="submitCard">提交</button>
data() {
return {
newCard: { title: '', content: '' }
}
},
methods: {
submitCard() {
this.cards.push({ ...this.newCard, id: Date.now() })
this.newCard = { title: '', content: '' } // 重置表单
}
}






