vue表格实现增删改
Vue表格实现增删改
基础表格结构
使用el-table组件构建基础表格,绑定数据源并定义列:
<template>
<el-table :data="tableData" style="width: 100%">
<el-table-column prop="name" label="姓名"></el-table-column>
<el-table-column prop="age" label="年龄"></el-table-column>
<el-table-column label="操作">
<template #default="scope">
<el-button @click="handleEdit(scope.row)">编辑</el-button>
<el-button @click="handleDelete(scope.row)">删除</el-button>
</template>
</el-table-column>
</el-table>
</template>
数据初始化
在data中定义表格数据和临时表单对象:
data() {
return {
tableData: [
{ id: 1, name: '张三', age: 25 },
{ id: 2, name: '李四', age: 30 }
],
form: {
id: '',
name: '',
age: ''
},
dialogVisible: false
}
}
新增功能实现
添加新增按钮和对话框表单:
<el-button @click="handleAdd">新增</el-button>
<el-dialog v-model="dialogVisible" title="表单">
<el-form :model="form">
<el-form-item label="姓名">
<el-input v-model="form.name"></el-input>
</el-form-item>
<el-form-item label="年龄">
<el-input v-model="form.age"></el-input>
</el-form-item>
</el-form>
<template #footer>
<el-button @click="dialogVisible = false">取消</el-button>
<el-button @click="submitForm">确定</el-button>
</template>
</el-dialog>
新增方法逻辑:
methods: {
handleAdd() {
this.form = { id: '', name: '', age: '' }
this.dialogVisible = true
},
submitForm() {
if (this.form.id) {
// 更新逻辑
} else {
this.form.id = Date.now()
this.tableData.push({...this.form})
}
this.dialogVisible = false
}
}
编辑功能实现
编辑方法逻辑:
handleEdit(row) {
this.form = { ...row }
this.dialogVisible = true
}
更新submitForm方法中的更新逻辑:
if (this.form.id) {
const index = this.tableData.findIndex(item => item.id === this.form.id)
this.tableData.splice(index, 1, {...this.form})
}
删除功能实现
删除方法逻辑:
handleDelete(row) {
this.$confirm('确认删除?', '提示').then(() => {
const index = this.tableData.findIndex(item => item.id === row.id)
this.tableData.splice(index, 1)
})
}
完整组件示例
<template>
<div>
<el-button @click="handleAdd">新增</el-button>
<el-table :data="tableData">
<!-- 表格列定义 -->
</el-table>
<!-- 对话框表单 -->
</div>
</template>
<script>
export default {
data() {
return {
tableData: [],
form: {},
dialogVisible: false
}
},
methods: {
// 所有方法实现
}
}
</script>
关键注意事项
- 使用
v-model实现表单双向绑定 - 操作数组时注意Vue的响应式规则,使用可触发视图更新的方法
- 对于复杂场景可考虑使用Vuex管理状态
- 实际项目中建议将表单验证逻辑加入
以上实现使用了Element UI组件库,如需使用其他UI库或原生实现,原理相同但具体API会有差异。







