1、js根据值递归筛选树结构
//搜索框
<a-input-search style="margin-bottom: 8px" placeholder="Search" @change="onChange" />
//树组件
<a-tree
:checkable="checkable"
:treeData="filterTreeData"
:checkedKeys.sync="checkedKeys"
@check="onCheck"
>
traverseTree(tree, value) {
let newarr = []
tree.forEach((node) => {
if (node.name.indexOf(value) > -1) {
newarr.push(node)
} else {
if (node.children&& node.children.length > 0) {
let child = this.traverseTree(node.children, value)
if (child && child.length > 0) {
let obj = {
...node,
children: child,
}
newarr.push(obj)
}
}
}
})
return newarr
},
onChange(e) {
const value = e.target.value
this.filterTreeData = this.traverseTree(this.treeData, value)
},
2、递归删除
deleteNode(tree) {
return tree.filter((node) => {
if (node.menuType === 3) {
return false
}
if (node.children) {
node.children = this.deleteNode(node.children)
}
return true
})
},
3、递归设置节点属性(selectable)
recursiveNode(tree) {
tree.forEach((item)=>{
if(!item.children || item.children.length == 0){
item.selectable = true
}
if(item.children && item.children.length >0){
item.selectable = false
this.recursiveNode(item.children)
}
})
return tree
},
4、递归匹配id,返回这个节点数据
findNodeById(tree, id) {
for (var i = 0; i < tree.length; i++) {
var node = tree[i]
if (node.id === id) {
return node
}
if (node.children && node.children.length > 0) {
var foundNode = this.findNodeById(node.children, id)
if (foundNode) {
return foundNode
}
}
}
return null
},
5、递归与数组匹配,返回新数组
findNodeByArr(tree, arr, newarr = []) {
tree.map((node) => {
if (arr.includes(node.id)) {
newarr.push({
id: node.id,
name: node.name,
})
}
if (node.childList && node.childList.length > 0) {
this.findNodeByArr(node.childList, arr, newarr)
}
})
return newarr
},