項目中使用了el-table 樹形結(jié)構(gòu)來展示數(shù)據(jù),并且可以直接編輯耀盗、新增數(shù)據(jù)。
項目截圖
將“id”作為row-key,expand-row-keys為數(shù)組“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);
},
手動增加了子目錄之后發(fā)現(xiàn)父級的行并沒有被展開妓布,開始疑惑并且尋找原因,仔細看了element-ui的文檔之后發(fā)現(xiàn)了問題
官方文檔
“類型為String時支持多層訪問” 宋梧,看到這句話明白了些什么開始修改匣沼,將row-key的“id”轉(zhuǎn)為String類型,新增子目錄時往expandRowKeys里push也記得轉(zhuǎn)換成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());
},
問題解決捂龄,試了一下可以正常打開了释涛,記得在手動展開關(guān)閉行的時候操作expandRowKeys數(shù)組中的數(shù)據(jù),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);
}
},