官方的例子
<el-tree
:props="props"
:load="loadNode"
lazy>
</el-tree>
<script>
export default {
data() {
return {
props: {
label: 'name',
children: 'zones',
isLeaf: 'leaf'
}
}
},
methods: {
loadNode(node, resolve) {
if (node.level === 0) {
return resolve([{ name: 'region' }]);
}
if (node.level > 1) return resolve([]);
setTimeout(() => {
const data = [
{
name: 'leaf',
leaf: true
},{
name: 'zone'
}
];
resolve(data);
}, 500);
}
}
</script>
官方的例子只是告诉我们可以使用 :load="loadNode"
进行加载子节点,每次点击箭头,然后会主动调用loadNode,通过resolve把需要添加的子节点添加到点击的node下,但是问题来了,如果我们的需求是动态的添加文件夹,这个时候就无能为力了...
实际的解决方案
refreshLazyTree(children){
let theChildren = this.currentNode.childNodes;
theChildren.splice(0, theChildren.length)
// 这个是看过源码Node.js中的,其实我们load最后也是会调用这个方法
this.currentNode.doCreateChildren(children)
},
解释:
-
- let theChild = this.currentNode.children; 这句话的意思就是获取选中的节点的子节点,也就是我们需要在哪个目录下添加文件夹。
-
- theChildren.splice(0, theChildren.length); 先删除此节点下的全部子元素
-
- this.currentNode.doCreateChildren(children); 其实这句话调用的就是源码中Node类的方法,它的作用就是通过数据,添加子节点。
-
- 注释:第三步中的children, 就是我们请求后台返回的数据,需要添加到该节点的子节点,和loadNode中resolve(data)其实是一样的。
总结
希望对遇到此类问题的伙伴能有所帮助,通过此事更能体现学习开源项目源码的重要性,如果遇到什么问题,可以留言,我会在时间宽裕的时候给与解答。