vue实现表格批量删除
Vue实现表格批量删除功能
核心思路:通过复选框选择多条数据,调用接口批量删除,并更新本地数据。
数据准备与表格渲染
在Vue组件中定义表格数据和选中项的数组:
data() {
return {
tableData: [], // 表格数据
multipleSelection: [], // 选中的数据
selectedIds: [] // 选中的ID集合
}
}
表格模板中使用el-table和el-checkbox:

<el-table
:data="tableData"
@selection-change="handleSelectionChange"
ref="multipleTable">
<el-table-column type="selection" width="55"></el-table-column>
<!-- 其他列 -->
</el-table>
选择项处理
实现选择变化时的回调方法:
methods: {
handleSelectionChange(val) {
this.multipleSelection = val;
this.selectedIds = val.map(item => item.id);
}
}
批量删除实现
删除方法需要处理接口调用和本地数据更新:

batchDelete() {
if (this.selectedIds.length === 0) {
this.$message.warning('请至少选择一条数据');
return;
}
this.$confirm('确认删除选中数据?', '提示', {
type: 'warning'
}).then(() => {
// 调用API
deleteItems(this.selectedIds).then(res => {
this.$message.success('删除成功');
// 过滤掉已删除的数据
this.tableData = this.tableData.filter(
item => !this.selectedIds.includes(item.id)
);
// 清空选择
this.$refs.multipleTable.clearSelection();
});
}).catch(() => {});
}
全选/反选功能增强
可添加全选按钮提升用户体验:
<el-button @click="toggleSelection">全选/反选</el-button>
<el-button @click="batchDelete" type="danger">批量删除</el-button>
对应方法实现:
toggleSelection() {
if (this.$refs.multipleTable) {
const $table = this.$refs.multipleTable;
$table.toggleAllSelection();
}
}
注意事项
- 删除操作前务必添加确认对话框
- 接口调用失败时需要处理错误情况
- 对于大量数据应考虑分页处理
- 删除后可能需要重新获取数据而非本地过滤(视业务需求而定)
性能优化建议
对于大型表格可考虑以下优化:
// 使用row-key提高渲染性能
<el-table row-key="id">
<!-- 列定义 -->
</el-table>
// 虚拟滚动优化(Element Plus支持)
<el-table-v2 :columns="columns" :data="data" :width="700" :height="400" />






