需求:el-table 懒加载模式下,刷新树数据,自动展开上次展开的节点。
说明:我这个案例是,先勾选记录,然后有个批量删除的按钮,点击一下,删除勾选的记录,然后刷新整个列表,此时列表会回到初始未展开状态,要实现的是自动展开刷新前展开的节点。
代码:
export default {
data() {
return {
// 树结构数据(懒加载的数据同步到 treeData 中的逻辑需要自己实现)
treeData: [],
cacheExpandedKeys: new Set()
}
},
methods: {
// 当 flag 为 true 恢复上次展开的节点,当为 false 时保存上次展开过的节点
handleExpandedRows(flag) {
if (flag) {
const fn = () => {
// 只要还有 key 一直执行下去
if (this.cacheExpandedKeys.size) {
for (const key of this.cacheExpandedKeys.keys()) {
const item = this.getItemByVal(key)
if (item) {
this.cacheExpandedKeys.delete(key) // 展开一个节点去除一个节点 key
this.$refs.tableData.$refs.table.toggleRowExpansion(item, true)
this.$refs.tableData.$refs.table.store.loadOrToggle(item)
}
}
setTimeout(fn, 500)
} else {
// 等全部展开完后,重置展开节点的 loading = false 因为自动展开后有的节点下拉图标一直处于 loading 状态(bug)
const treeData = this.$refs.tableData.$refs.table.store.states.treeData
for (const key in treeData) {
if (treeData[key].expanded) {
treeData[key].loading = false
}
}
}
}
fn()
} else {
this.cacheExpandedKeys.clear()
const treeData = this.$refs.tableData.$refs.table.store.states.treeData
for (const key in treeData) {
// selectionRows 是选中的节点,如果上次展开的节点包含在被选中的节点中,则不保存
const isDelete = this.selectionRows.findIndex(item => item.id === key) === -1
if (isDelete && treeData[key].expanded) {
// 保存展开过的节点 key
this.cacheExpandedKeys.add(key)
}
}
}
},
getItemByVal(val) {
const key = 'id'
const children = 'children'
const fn = (nodes, val) => {
for (const node of nodes) {
if (node[key] === val) return node
if (node[children] && node[children].length > 0) {
const obj = fn(node[children], val)
if (obj) return obj
}
}
}
return fn(this.treeData, val)
}
}
}