vue实现添加卡片
实现添加卡片功能
在Vue中实现添加卡片功能通常涉及组件设计、数据管理和用户交互。以下是具体实现方法:
创建卡片组件
新建一个卡片组件Card.vue:

<template>
<div class="card">
<h3>{{ title }}</h3>
<p>{{ content }}</p>
<button @click="$emit('delete')">删除</button>
</div>
</template>
<script>
export default {
props: {
title: String,
content: String
}
}
</script>
<style scoped>
.card {
border: 1px solid #ddd;
padding: 15px;
margin: 10px;
border-radius: 5px;
}
</style>
管理卡片数据
在父组件中管理卡片数据:
<template>
<div>
<button @click="addCard">添加卡片</button>
<div v-for="(card, index) in cards" :key="index">
<Card
:title="card.title"
:content="card.content"
@delete="deleteCard(index)"
/>
</div>
</div>
</template>
<script>
import Card from './Card.vue'
export default {
components: { Card },
data() {
return {
cards: []
}
},
methods: {
addCard() {
this.cards.push({
title: `卡片 ${this.cards.length + 1}`,
content: '这是卡片内容'
})
},
deleteCard(index) {
this.cards.splice(index, 1)
}
}
}
</script>
添加表单输入
如果需要用户自定义卡片内容,可以添加表单:

<template>
<div>
<input v-model="newCard.title" placeholder="标题">
<textarea v-model="newCard.content" placeholder="内容"></textarea>
<button @click="addCard">添加卡片</button>
<!-- 卡片列表 -->
</div>
</template>
<script>
export default {
data() {
return {
newCard: {
title: '',
content: ''
},
cards: []
}
},
methods: {
addCard() {
if (this.newCard.title.trim()) {
this.cards.push({...this.newCard})
this.newCard.title = ''
this.newCard.content = ''
}
}
}
}
</script>
使用Vuex管理状态
对于大型应用,可以使用Vuex集中管理卡片状态:
// store.js
export default new Vuex.Store({
state: {
cards: []
},
mutations: {
ADD_CARD(state, card) {
state.cards.push(card)
},
DELETE_CARD(state, index) {
state.cards.splice(index, 1)
}
},
actions: {
addCard({ commit }, card) {
commit('ADD_CARD', card)
},
deleteCard({ commit }, index) {
commit('DELETE_CARD', index)
}
}
})
动画效果
为卡片添加过渡动画:
<template>
<transition-group name="card-list" tag="div">
<Card v-for="(card, index) in cards" :key="card.id" />
</transition-group>
</template>
<style>
.card-list-enter-active, .card-list-leave-active {
transition: all 0.5s;
}
.card-list-enter, .card-list-leave-to {
opacity: 0;
transform: translateY(30px);
}
</style>
这些方法涵盖了Vue中添加卡片功能的基本实现,可以根据具体需求进行组合或扩展。






