不居家办公了,有点不习惯。
需求:
现有一棵选择人员树 (懒加载),希望通过搜索部门,快速定位到想选的人员。
后台返给我的搜索结果是一棵普通树 (非懒加载),且结果可能多个(部门之间可能重名)
用户点击搜索结果树的末级节点,可以通过之前的懒加载接口进行查找下级节点 (此节点及以下懒加载)
搜索部门名称:DEMO检查,后台返回DEMO检查一 和DEMO检查二,点击展开懒加载出节点 机关
解决思路
el树是无法实现部分节点懒加载的。当搜索时,备份返回的数据,后续渲染展开子节点时,需要前端模拟懒加载,遍历找到相应节点数据放入树里(注意此处应使用广度优先遍历)
实现过程
- 监听搜索字段deptName,当内容改变时,如果值不为空,则走搜索部门的接口,反之走懒加载接口
// 按部门搜索树
deptName (val) {
if (this.node) { // 初次加载树时备份根节点
this.node.childNodes = [] // 清空子节点
if (val) {
this.getOrgListSearch(this.node, this.resolve) // 再次执行 load 的方法
} else {
this.getOrgListAll(this.node, this.resolve) // 再次执行 load 的方法
}
}
}
- 树加载第一层(node.level === 0)时,备份返回的数据用于遍历渲染子节点
- 树加载子节点时
❤ 搜索部门时,返回当前节点层级数据(模拟懒加载)
deptDataCur (tree, func) {
let node, curTree = [...tree]
while ((node = curTree.shift())) {
const back = func(node)
if (back) { // 找到了,终止
break
}
node.children && curTree.push(...node.children) // 广度优先
}
},
❤ 懒加载方法
if (node.level === 0) {
...调用搜索部门接口,备份结果this.curNodeData
} else {
// 懒加载子节点
this.deptDataCur(this.curNodeData, item => {
if (item.id === node.data.id) {
this.curDeptDatas = item.children // 获取当前节点数据
return true
}
})
//如果有数据,将数据放入树对象;否则走懒加载接口加载子节点
if(this.curDeptDatas && this.curDeptDatas.length) {
//塞入数据
node.data.children = this.curDeptDatas
resolve(node.data.children)
// 自动展开加载下级节点
const nodedata = node.childNodes[0]
nodedata.expanded = true
nodedata.loadData()
} else {
...调用懒加载接口
}
}
- 另外
可以通过
this.$refs.tree2.setCurrentKey(this.curNodeKey) 设置初始高亮节点
和
this.$refs.tree2.setCheckedNodes(this.keyarr) 设置初始checked节点