elementUI 如何动态的给 el-tree 添加子节点数据 children

一、需求

有这样一个数据结构的 tree。

elementUI 如何动态的给 el-tree 添加子节点数据 children_vue.js


​element​​ 的 tree 懒加载是从根上就开始懒加载,但我需要实现的是已经存在一个层级的 tree 结构,只是在末端点击的时候,载入末端以下的列表。

二、实现

1. tree 的实例事件 ​​node-click​

我们就不能用它的懒加载方法了,而是使用 ​​node-click​​ 这个事件

<el-tree
ref="treeNav"
:indent="10"
:default-expanded-keys="defaultExpandedKeys"
@node-click="treeNodeClicked"
:data="treeData"
:highlight-current="true"
node-key="id">
</el-tree>

当点击的事件说明:

elementUI 如何动态的给 el-tree 添加子节点数据 children_elementui_02

点击的时候你获取到了:当前被点击节点的完整数据,你只需要

  1. 用其中的​​id​​ 或者其它自己定义的标识字段,去获取对应的数据
  2. 然后再格式化成​​tree​​ 的数据
  3. 重新赋值给当前节点的​​children​​ 字段即可

2. tree 的实例方法:​​updateKeyChildren​

此时你还需要用到 tree 的另一个方法: ​​updateKeyChildren​​。

其作用的就是根据你提供的节点的 ​​id​​​,设置这个节点的 ​​children​​ 数据,刚好是要用到的。

elementUI 如何动态的给 el-tree 添加子节点数据 children_懒加载_03

3. 自动展示当前被点击的节点

点击并插入当前节点的 ​​children​​ 数据之后,需要它自动展开

只需要设置 ​​tree​​​ 参数中的 ​​default-expanded-keys​​​ 为当前节点的 ​​key​​ 即可

this.defaultExpandedKeys = [nodeData.id]

4. 页面重新加载后,定位到当前的位置

页面的 url 参数中保留几个参数: ​​projectid​​​ ​​devicename​​​ ​​index​

  1. 页面重载之后,用 projectid 来获取内部数据
  2. 添加到已有的树结构中
  3. 再使用 tree 组件的 setCurrentNode(nodeKey) 方法来选中该选中的节点

当然,这个实现过程还是有点繁琐的。

页面重新刷新,其结果就是:

elementUI 如何动态的给 el-tree 添加子节点数据 children_javascript_04

// 存在 projectId 时,加载对应项目的 preview 信息,并定位到之前的设备位置
if (this.currentProjectId){
this.getProjectPreviewOf(this.currentProjectId, projectPreview => {
let checkedKey = `project-${this.currentProjectId}:${this.deviceName}`
this.$refs.treeNav.setCurrentKey(checkedKey)
this.SET_CURRENT_DEVICE_LIST(projectPreview[this.deviceName])
})
}

5. 参考代码

// 根据 projectId 获取对应项目的 preview
getProjectPreviewOf(nodeData){
areaApi
.previewOfProject({
pid: nodeData.projectInfo.id
})
.then(res => {
let treeDataForPreview = this.getTreeDataFromPreview(res, nodeData.projectInfo.id)
console.log('Tree data for preview: ',treeDataForPreview)
this.$refs.treeNav.updateKeyChildren(nodeData.id, treeDataForPreview)
// 展开当前节点
this.defaultExpandedKeys = [nodeData.id]
// 默认展示:当前项目的第一个设备类型的设备
this.SET_CURRENT_DEVICE_LIST(treeDataForPreview[0].deviceInfos)
})
},

三、结果

elementUI 如何动态的给 el-tree 添加子节点数据 children_elementui_05