vue实现增删改功能
Vue 实现增删改功能
在 Vue 中实现增删改功能通常涉及数据绑定、事件处理和状态管理。以下是一个完整的实现方案,涵盖增删改查(CRUD)的核心逻辑。
数据初始化
在 Vue 组件的 data 中定义初始数据列表和表单对象:
data() {
return {
items: [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' }
],
form: {
id: null,
name: ''
},
editing: false
}
}
新增功能
通过表单绑定 v-model 并触发添加方法:
<input v-model="form.name" placeholder="Enter name">
<button @click="addItem">Add</button>
methods: {
addItem() {
if (!this.form.name) return
this.items.push({
id: Math.max(...this.items.map(i => i.id)) + 1,
name: this.form.name
})
this.resetForm()
},
resetForm() {
this.form = { id: null, name: '' }
this.editing = false
}
}
删除功能
通过索引或唯一标识符删除数据:
<ul>
<li v-for="(item, index) in items" :key="item.id">
{{ item.name }}
<button @click="deleteItem(index)">Delete</button>
</li>
</ul>
methods: {
deleteItem(index) {
this.items.splice(index, 1)
}
}
编辑功能
实现编辑需要先填充表单再更新数据:
<button @click="editItem(item)">Edit</button>
methods: {
editItem(item) {
this.form = { ...item }
this.editing = true
},
updateItem() {
const index = this.items.findIndex(i => i.id === this.form.id)
this.items.splice(index, 1, { ...this.form })
this.resetForm()
}
}
条件渲染提交按钮
根据编辑状态切换按钮功能:
<button @click="editing ? updateItem() : addItem()">
{{ editing ? 'Update' : 'Add' }}
</button>
完整组件示例
<template>
<div>
<input v-model="form.name" placeholder="Enter name">
<button @click="editing ? updateItem() : addItem()">
{{ editing ? 'Update' : 'Add' }}
</button>
<ul>
<li v-for="(item, index) in items" :key="item.id">
{{ item.name }}
<button @click="editItem(item)">Edit</button>
<button @click="deleteItem(index)">Delete</button>
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' }
],
form: {
id: null,
name: ''
},
editing: false
}
},
methods: {
addItem() {
if (!this.form.name) return
this.items.push({
id: Math.max(...this.items.map(i => i.id)) + 1,
name: this.form.name
})
this.resetForm()
},
editItem(item) {
this.form = { ...item }
this.editing = true
},
updateItem() {
const index = this.items.findIndex(i => i.id === this.form.id)
this.items.splice(index, 1, { ...this.form })
this.resetForm()
},
deleteItem(index) {
this.items.splice(index, 1)
},
resetForm() {
this.form = { id: null, name: '' }
this.editing = false
}
}
}
</script>
关键点说明
- 数据驱动:所有操作直接修改
items数组,Vue 自动更新 DOM - 唯一标识:使用
id确保操作准确性,避免直接依赖数组索引 - 表单复用:通过
editing状态切换添加/编辑模式 - 响应式更新:数组方法如
push/splice会触发视图更新
对于复杂场景,建议使用 Vuex 或 Pinia 管理状态,组件间通过 props/events 通信。







