vue实现增加修改
Vue 实现增加和修改功能
数据绑定与表单处理
使用 v-model 实现表单数据的双向绑定,适用于新增和修改场景。例如表单输入框绑定到 formData 对象:
<template>
<input v-model="formData.name" placeholder="请输入名称">
<input v-model="formData.age" type="number" placeholder="请输入年龄">
</template>
<script>
export default {
data() {
return {
formData: { name: '', age: null }
}
}
}
</script>
新增数据逻辑
通过方法将表单数据添加到列表,并重置表单:
methods: {
addItem() {
this.items.push({ ...this.formData });
this.resetForm();
},
resetForm() {
this.formData = { name: '', age: null };
}
}
修改数据逻辑
设置编辑状态和当前编辑项索引,填充表单数据:
editItem(index) {
this.editingIndex = index;
this.formData = { ...this.items[index] };
},
updateItem() {
this.items.splice(this.editingIndex, 1, { ...this.formData });
this.cancelEdit();
}
状态管理
使用 editingIndex 区分新增和编辑模式:
data() {
return {
editingIndex: -1,
items: []
}
}
动态按钮与条件渲染
根据编辑状态显示不同操作按钮:
<button @click="editingIndex === -1 ? addItem() : updateItem()">
{{ editingIndex === -1 ? '添加' : '更新' }}
</button>
<button v-if="editingIndex !== -1" @click="cancelEdit">取消</button>
完整组件示例
<template>
<div>
<input v-model="formData.name">
<input v-model="formData.age" type="number">
<button @click="handleSubmit">
{{ editingIndex === -1 ? '添加' : '更新' }}
</button>
<ul>
<li v-for="(item, index) in items" :key="index">
{{ item.name }} - {{ item.age }}
<button @click="editItem(index)">编辑</button>
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
formData: { name: '', age: null },
items: [],
editingIndex: -1
}
},
methods: {
handleSubmit() {
if (this.editingIndex === -1) {
this.items.push({ ...this.formData });
} else {
this.items.splice(this.editingIndex, 1, { ...this.formData });
}
this.resetForm();
},
editItem(index) {
this.formData = { ...this.items[index] };
this.editingIndex = index;
},
resetForm() {
this.formData = { name: '', age: null };
this.editingIndex = -1;
}
}
}
</script>






