vue实现添加删除
Vue 实现添加和删除功能
在 Vue 中实现添加和删除功能通常涉及数据绑定、事件处理和列表渲染。以下是具体实现方法:
添加功能实现
-
在 Vue 实例的 data 中定义一个数组来存储数据项:
data() { return { items: [], newItem: '' } } -
在模板中添加输入框和按钮:
<input v-model="newItem" placeholder="输入新项目"> <button @click="addItem">添加</button> -
实现添加方法:
methods: { addItem() { if (this.newItem.trim()) { this.items.push(this.newItem.trim()) this.newItem = '' } } }
删除功能实现
-
使用 v-for 渲染列表并为每个项目添加删除按钮:
<ul> <li v-for="(item, index) in items" :key="index"> {{ item }} <button @click="removeItem(index)">删除</button> </li> </ul> -
实现删除方法:

methods: { removeItem(index) { this.items.splice(index, 1) } }
完整示例代码
<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>
<script>
export default {
data() {
return {
items: [],
newItem: ''
}
},
methods: {
addItem() {
if (this.newItem.trim()) {
this.items.push(this.newItem.trim())
this.newItem = ''
}
},
removeItem(index) {
this.items.splice(index, 1)
}
}
}
</script>
注意事项
- 使用 v-model 实现双向数据绑定
- 为列表项添加唯一的 key 属性
- 使用数组的 push 和 splice 方法修改数据
- 确保在修改数据前进行必要的验证
- 考虑添加确认对话框以防止误删除






