element 树形表在懒加载模式下官方没有提供实时局部刷新节点的方法,在网上看了好多博客也没有比较好的办法
源码中tree.js懒加载的一个方法:
loadData(row, key, treeNode) {
const { load } = this.table;
const { lazyTreeNodeMap, treeData } = this.states;
if (load && !treeData[key].loaded) {
treeData[key].loading = true;
load(row, treeNode, (data) => {
if (!Array.isArray(data)) {
throw new Error('[ElTable] data must be an array');
}
treeData[key].loading = false;
treeData[key].loaded = true;
treeData[key].expanded = true;
if (data.length) {
this.$set(lazyTreeNodeMap, key, data);
}
this.table.$emit('expand-change', row, true);
});
}
}
element 在每次更新节点时都调用了该方法,其中的load方法就是我们绑定的懒加载方法;最终发现它实现节点更新的关键在于:
this.$set(lazyTreeNodeMap, key, data)
lazyTreeNodeMap:this.$refs.table.store.states.lazyTreeNodeMap
key:就是table-key
data:节点的children数组
于是写一个更新某个节点的子节点的方法:
refreshRow(id){
this.$api.getList({ pid: id }).then(res => {
if (res.success) {
this.$set(this.$refs.table.store.states.lazyTreeNodeMap, id, res.data.dataList)
}
})
}
在增加和删除后更新该节点的父节点(调用以上方法)即可。
实际代码:
<template lang="pug">
el-table.header-center(
ref="asyncTree"
:height="tableHeight"
v-loading="loading"
element-loading-text="数据加载中..."
row-key="id"
node-key="id"
:data="tableData"
stripe border lazy
:load="loadChildren"
:tree-props="{children: 'childs', hasChildren: 'child'}"
)
</template>
<script lang="ts">
// ....
async loadData(index: number = 1) {
this.pagination.current = index
let param: any = {pid: 0}
if (this.keyword.length > 0) {
param.name = this.keyword
}
if (this.pagination.enable) {
param.pageIndex = this.pagination.current
}
this.loading = true
this.tableData = []
const res = await this.$api.region.list(param)
const data = res.data
this.tableData = data
if(this.pagination.enable) {
const page = {total: res.page.totalCount, current: res.page.pageIndex, size: res.page.pageSize}
this.pagination = Object.assign({}, this.pagination, page)
}
this.loading = false
return data
}
async loadChildren(tree, treeNode, resolve) {
this.mapTableData.set(tree.id, {tree, treeNode, resolve})
const data = await this.refreshRow(tree.id)
resolve(data)
}
/**
* 懒加载数刷新子节点
* @param id
*/
async refreshRow(id = 0) {
if (id == 0) return await this.loadData()
const res = await this.$api.region.list({pid: id})
this.$set(this.$refs["asyncTree"].store.states.lazyTreeNodeMap, id, res.data)
return res.data
}
remove(item, scope) {
// remove logic
this.refreshRow(item.pid)
}
</script>