最近在用vue + elementui 开发后台操作系统,项目需求有嵌套表格table
html :
<el-table :data="tableData" highlight-current-row @row-click="rowClick" :row-
key="getRowKeys" :expand-row-keys="expands" @expand-change="expandSelect"
border size="mini" class="table" ref="tableList" header-cell-class-name="table-header">
<el-table-column prop="id" label="ID" width="90" align="center" type="expand">
<template slot-scope="props">
<el-table :data="props.row.children" border height="220" size="mini" :header-row-class-name="tableChildrenHeader" style="width: 100%">
<el-table-column prop="oilTypeName" label="油品类型" width="180"> </el-table-column>
<el-table-column prop="oilName" label="油品名称" width="180"> </el-table-column>
<el-table-column prop="oilTankCode" label="油罐号" width="180"> </el-table-column>
<el-table-column prop="oilGunCode" label="枪号"> </el-table-column>
<el-table-column prop="oilPrice" label="当前价"> </el-table-column>
<el-table-column prop="modifyOilPrice" label="调整价"> </el-table-column>
<el-table-column prop="tzl" label="调整量"></el-table-column>
</el-table>
</template>
</el-table-column>
</el-table>
<script>
data(){
return {
expands: [], // 目前的展开行
getRowKeys(row){
return row.oilPriceRecordId
}
}
}
</script>
js 部分:
rowClick(row){//点击行时展开收起
this.$refs.tableList.toggleRowExpansion(row);
},
// 当用户对某一行展开或者关闭的时候会触发该事件
expandSelect(row, expandedRows) {
this.tableData.forEach((item,index)=>{
// 2 清空很重要,不然会报错 key 错误
this.tableData[index].children = [];
if (expandedRows.length) {
this.expands = [];
if (row) {
this.expands.push(row.oilPriceRecordId)//只展开当前行id
if(item.oilPriceRecordId == row.oilPriceRecordId ){
getOilPriceRecord({oilPriceRecordId: row.oilPriceRecordId }).then(res=>{
if(res.code == 0){
this.tableData[index].children = res.data.map(item=>{
item['tzl'] = (Number(item.modifyOilPrice) - Number(item.oilPrice)).toFixed(2);
return item
});
}
})
}
}
} else {
this.expands = []
}
})
},
注意点:
1、 在展开或者关闭特定行时,记得及时清空上次数据;
2、因为展开行 type="expand" 三角范围很小,不容易被点击,可以增加 row-click 扩大点击范围;
3、数据可以不放在一级表格中,我这是自行的数据结构,小伙伴可以自行拓展哦~