vue实现添加和删除
Vue 实现添加和删除功能
在 Vue 中实现添加和删除功能通常涉及数据绑定、事件处理和列表渲染。以下是实现这些功能的具体方法:
数据绑定与初始化
在 Vue 组件的 data 或 setup 中初始化一个数组来存储需要操作的数据。例如:
data() {
return {
items: ['Item 1', 'Item 2', 'Item 3'],
newItem: ''
}
}
或使用 Composition API:
setup() {
const items = ref(['Item 1', 'Item 2', 'Item 3']);
const newItem = ref('');
return { items, newItem };
}
添加功能实现
通过表单输入绑定 v-model 获取新数据,并在按钮点击时触发添加逻辑:
<input v-model="newItem" placeholder="Add new item">
<button @click="addItem">Add</button>
对应的方法:
methods: {
addItem() {
if (this.newItem.trim() !== '') {
this.items.push(this.newItem.trim());
this.newItem = '';
}
}
}
或 Composition API:
const addItem = () => {
if (newItem.value.trim() !== '') {
items.value.push(newItem.value.trim());
newItem.value = '';
}
};
删除功能实现
使用 v-for 渲染列表,并为每个项添加删除按钮。通过索引或唯一标识符删除数据:
<ul>
<li v-for="(item, index) in items" :key="index">
{{ item }}
<button @click="removeItem(index)">Delete</button>
</li>
</ul>
对应的删除方法:
methods: {
removeItem(index) {
this.items.splice(index, 1);
}
}
或 Composition API:
const removeItem = (index) => {
items.value.splice(index, 1);
};
完整示例(Options API)
<template>
<div>
<input v-model="newItem" placeholder="Add new item">
<button @click="addItem">Add</button>
<ul>
<li v-for="(item, index) in items" :key="index">
{{ item }}
<button @click="removeItem(index)">Delete</button>
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
items: ['Item 1', 'Item 2', 'Item 3'],
newItem: ''
};
},
methods: {
addItem() {
if (this.newItem.trim() !== '') {
this.items.push(this.newItem.trim());
this.newItem = '';
}
},
removeItem(index) {
this.items.splice(index, 1);
}
}
};
</script>
完整示例(Composition API)
<template>
<div>
<input v-model="newItem" placeholder="Add new item">
<button @click="addItem">Add</button>
<ul>
<li v-for="(item, index) in items" :key="index">
{{ item }}
<button @click="removeItem(index)">Delete</button>
</li>
</ul>
</div>
</template>
<script setup>
import { ref } from 'vue';
const items = ref(['Item 1', 'Item 2', 'Item 3']);
const newItem = ref('');
const addItem = () => {
if (newItem.value.trim() !== '') {
items.value.push(newItem.value.trim());
newItem.value = '';
}
};
const removeItem = (index) => {
items.value.splice(index, 1);
};
</script>
关键点
- 数据驱动:Vue 的核心是数据绑定,通过修改数组(如
push或splice)自动更新视图。 - 唯一标识:
v-for中的:key必须唯一,通常使用索引或数据 ID。 - 事件处理:使用
@click绑定方法,注意传递参数(如索引)。
以上方法适用于大多数简单场景,如需复杂操作(如后端交互),可结合 axios 或 fetch 扩展逻辑。







