vue实现添加删除
Vue 实现添加和删除功能
在 Vue 中实现添加和删除功能通常涉及数据绑定、事件处理和列表渲染。以下是实现方法:
数据绑定与列表渲染
使用 v-for 指令渲染列表,并通过 v-model 绑定输入数据:
<template>
<div>
<input v-model="newItem" placeholder="输入新项">
<button @click="addItem">添加</button>
<ul>
<li v-for="(item, index) in items" :key="index">
{{ item }}
<button @click="removeItem(index)">删除</button>
</li>
</ul>
</div>
</template>
添加功能实现
在 Vue 实例的 methods 中定义 addItem 方法,将新项添加到数组:
<script>
export default {
data() {
return {
newItem: '',
items: []
}
},
methods: {
addItem() {
if (this.newItem.trim()) {
this.items.push(this.newItem)
this.newItem = ''
}
}
}
}
</script>
删除功能实现
通过数组的 splice 方法移除指定索引的项:
methods: {
removeItem(index) {
this.items.splice(index, 1)
}
}
使用计算属性优化
对于需要派生状态的情况(如空值检查),可以使用计算属性:
computed: {
isInputEmpty() {
return this.newItem.trim() === ''
}
}
添加动画效果
通过 Vue 的 <transition-group> 为列表添加动画:
<transition-group name="list" tag="ul">
<li v-for="(item, index) in items" :key="index">
{{ item }}
<button @click="removeItem(index)">删除</button>
</li>
</transition-group>
完整组件示例
<template>
<div>
<input
v-model="newItem"
placeholder="输入新项"
@keyup.enter="addItem"
>
<button
@click="addItem"
:disabled="isInputEmpty"
>
添加
</button>
<transition-group name="fade" tag="ul">
<li v-for="(item, index) in items" :key="index">
{{ item }}
<button @click="removeItem(index)">删除</button>
</li>
</transition-group>
</div>
</template>
<script>
export default {
data() {
return {
newItem: '',
items: []
}
},
computed: {
isInputEmpty() {
return this.newItem.trim() === ''
}
},
methods: {
addItem() {
if (!this.isInputEmpty) {
this.items.push(this.newItem.trim())
this.newItem = ''
}
},
removeItem(index) {
this.items.splice(index, 1)
}
}
}
</script>
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.5s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
</style>






