el-table实现表格动态新增/插入/删除 表格行,可编辑单元格
效果如下:
- 点击“新增一行”可以在表格最后新增一行,单元格内容可编辑
- 点击绿色+按钮,可在指定行的后面插入一行
- 点击红色-按钮,可以删除指定行
原理:表格el-table
是通过动态循环tableData
生成,只要对tableData
数组进行增加删除元素,就可以达到效果
这里用了element的el-table
,也可以用原生,道理一样
<template><div class="container"><el-buttontype="primary"size="mini"icon="el-icon-circle-plus-outline"@click="addRow"style="margin-bottom: 20px">新增一行</el-button><el-table :data="tableData" border><el-table-columnlabel="序号"align="center"type="index"fixedsortable/><el-table-column label="列1" prop="colcumn1" align="center"><template slot-scope="scope"><div class="flex align-center"><el-input v-model="scope.row.colcumn1" /></div></template></el-table-column><el-table-column label="列2" prop="colcumn1" align="center"><template slot-scope="scope"><div class="flex align-center"><el-input v-model="scope.row.colcumn2" /></div></template></el-table-column><el-table-column label="操作" align="center"><template slot-scope="scope"><el-buttontype="success"icon="el-icon-plus"circlesize="small"@click="addRowIndex(scope.$index)"></el-button><el-buttontype="danger"icon="el-icon-minus"circlesize="small"@click="delRow(scope.$index)"></el-button></template></el-table-column></el-table></div>
</template><script>
export default {name: "test",data() {return {tableData: [],};},mounted() {},methods: {// 增加一行addRow() {const row = {colcumn1: "",colcumn2: "",};this.tableData.push(row);},// 删除指定行delRow(index) {this.tableData.splice(index, 1);},// 指定位置插入行addRowIndex(index) {const row = {colcumn1: "",colcumn2: "",};this.tableData.splice(index + 1, 0, row);},},
};
</script><style scoped>
.container {padding: 50px;
}
</style>