ElementUI el-tree 懒加载模式的节点刷新
2025年6月6日大约 1 分钟
ElementUI el-tree 懒加载模式的节点刷新
在 lazy=true
模式的 el-tree 中,节点通过 load
方法加载。如果有需要手动刷新节点数据的需求,可以使用以下方法:
data
return {
treeRootNode: null
}
template
<el-tree lazy :load="loadData" :props="{isLeaf: 'leaf'}">
<!-- 内容省略-->
</el-tree>
懒加载方法
function loadData(node, resolve){
if (node.level === 0){
this.nasSourceApi.listPath("/").then(data=>{
this.treeRootNode = node // 加载根节点时保存跟节点
resolve(this.normalizeNASFileData(data))
})
}else {
// 其他节点加载方法省略
}
}
重新加载根节点
重新加载之前保存的 node 下的数据,node 可以是任何其他层级 node,该方法可以做到刷新任意节点下的数据。
function refreshNode(){
//节点刷新
if (this.treeRootNode){
this.treeRootNode.loaded = false // 设置根节点状态为未加载
this.treeRootNode.expand() // 调用 expand 方法,如果 loaded == false,node对象会主动调用 load 方法
}
}
Node 源码分析
expand(callback, expandParent) {
const done = () => {
if (expandParent) {
let parent = this.parent;
while (parent.level > 0) {
parent.expanded = true;
parent = parent.parent;
}
}
this.expanded = true;
if (callback) callback();
};
if (this.shouldLoadData()) { // this.store.lazy === true && this.store.load && !this.loaded; 这一步判断 loaded 是否为 false
this.loadData((data) => { // 这一步调用 store.load(node, resolve),也就是 el-tree 的 load 方法
if (data instanceof Array) {
if (this.checked) {
this.setChecked(true, true);
} else if (!this.store.checkStrictly) {
reInitChecked(this);
}
done();
}
});
} else {
done();
}
}