最近项目有一个需求,使用
el-table
显示表格数据,在显示的每一行中都有按钮,点击会展开显示这一行对应的子表数据,然后研究了一下,下面看下实现的方法。
1.控制展开还是折叠的操作按钮
<el-table-column label="" width="61">
<template slot-scope="scope">
//这里用 expandItem 属性用来存储上一次点击的是哪行数据,以此来判断是展开还是折叠,显示向右或是向下的箭头
<i :class="expandItem.dictId == scope.row.dictId ? 'el-icon-arrow-down' : 'el-icon-arrow-right'" @click="toogleExpand(scope.row)" style="cursor: pointer;"></i>
</template>
</el-table-column>
2.要折叠或展开的内容部分
<el-table-column type="expand" width="1">
<template slot-scope="scope">
<el-table :data="scope.row.caseReportList" style="width:90%">
<el-table-column prop="dictCode" label="字典编码">
</el-table-column>
<el-table-column prop="dictLabel" label="字典标签">
</el-table-column>
...
</el-table>
</template>
</el-table-column>
3.点击展开或折叠按钮执行的方法
//在 data 中定义一个属性,用来存储上一次点击的位置
expandItem:{dictId:null},
//实现点击按钮切换展开或折叠的方法
toogleExpand(row) {
const _this = this;
let table = _this.$refs.table;
if(this.expandItem == row){
//上一次点击和本地点击的是同一行,则折叠该行
table.toggleRowExpansion(row, false);
//重置上一次点击的行数据状态
this.expandItem = {dictId:null};
return;
}
//遍历数组,判断此次点击的是哪一行数据
_this.tableData.map((item, index) => {
if (row.dictId != item.dictId) {
//折叠
table.toggleRowExpansion(item, false);
}else{
//展开
table.toggleRowExpansion(item, true);
_this.expandItem = item;
//这里是我展开行以后,请求的对应行的子表数据请求方法
_this.requestRowList(row.dictType);
}
});
},
到这里,展开折叠效果就已经轻松实现了。
网友评论