项目中使用了el-table 树形结构来展示数据,并且可以直接编辑、新增数据。
将“id”作为row-key,expand-row-keys为数组“expandRowKeys”,代码如下:
<el-table
:data="configurationList"
:expand-row-keys="expandRowKeys"
:row-key="id}"
:tree-props="{ children: 'children' }"
:header-cell-style="tableHeaderCellStyle"
ref="treeTable"
@expand-change="expandChange"
></el-table>
JS:
addTemplate(parentId, row) {
let index = this.configurationList.length + 1;
this.configurationList.push({
isAdd: true,
no: index,
parentId: parentId,
id: new Date().getTime()
});
this.expandRowKeys.push(row.id);
},
手动增加了子目录之后发现父级的行并没有被展开,开始疑惑并且寻找原因,仔细看了element-ui的文档之后发现了问题
“类型为String时支持多层访问” ,看到这句话明白了些什么开始修改,将row-key的“id”转为String类型,新增子目录时往expandRowKeys里push也记得转换成String类型
<el-table
:data="configurationList"
:expand-row-keys="expandRowKeys"
:row-key="row => { return row.id.toString() }"
:tree-props="{ children: 'children' }"
:header-cell-style="tableHeaderCellStyle"
ref="treeTable"
@expand-change="expandChange"
></el-table>
JS:
addTemplate(parentId, row) {
let index = this.configurationList.length + 1;
this.configurationList.push({
isAdd: true,
no: index,
parentId: parentId,
id: new Date().getTime()
});
this.expandRowKeys.push(row.id.toString());
},
问题解决,试了一下可以正常打开了,记得在手动展开关闭行的时候操作expandRowKeys数组中的数据,row-key一定要保持唯一
expandChange(row, expanded) {
if (expanded) {
if (this.expandRowKeys.indexOf(row.id.toString()) < 0) {
this.expandRowKeys.push(row.id.toString());
}
} else {
this.expandRowKeys.splice(this.expandRowKeys.indexOf(row.id.toString()), 1);
}
},