vue实现表单添加删除
Vue 表单添加与删除实现
数据绑定与表单结构
使用v-model绑定表单数据,确保双向数据流。表单结构需包含输入字段和操作按钮。
<template>
<div>
<form @submit.prevent="addItem">
<input v-model="newItem.name" placeholder="名称">
<input v-model="newItem.age" placeholder="年龄" type="number">
<button type="submit">添加</button>
</form>
</div>
</template>
数据初始化
在data或setup中初始化表单数据和列表数组。
data() {
return {
newItem: { name: '', age: null },
items: []
}
}
添加功能实现
通过数组方法将新数据添加到列表中,并重置表单。
methods: {
addItem() {
this.items.push({...this.newItem});
this.newItem = { name: '', age: null };
}
}
删除功能实现
使用splice或filter根据索引或ID删除指定项。
<ul>
<li v-for="(item, index) in items" :key="index">
{{ item.name }} - {{ item.age }}
<button @click="removeItem(index)">删除</button>
</li>
</ul>
methods: {
removeItem(index) {
this.items.splice(index, 1);
}
}
使用计算属性验证
添加表单验证逻辑,确保数据有效性。
computed: {
isFormValid() {
return this.newItem.name.trim() && this.newItem.age > 0;
}
}
完整组件示例
整合所有功能的完整组件代码示例。
<template>
<div>
<form @submit.prevent="addItem">
<input v-model="newItem.name" placeholder="名称">
<input v-model="newItem.age" placeholder="年龄" type="number">
<button type="submit" :disabled="!isFormValid">添加</button>
</form>
<ul>
<li v-for="(item, index) in items" :key="index">
{{ item.name }} - {{ item.age }}
<button @click="removeItem(index)">删除</button>
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
newItem: { name: '', age: null },
items: []
}
},
computed: {
isFormValid() {
return this.newItem.name.trim() && this.newItem.age > 0;
}
},
methods: {
addItem() {
this.items.push({...this.newItem});
this.newItem = { name: '', age: null };
},
removeItem(index) {
this.items.splice(index, 1);
}
}
}
</script>






