a-tree的搜索功能,可以按照自己需求来做
<a-input-search style="margin-bottom: 8px"
@search="onSearch"
allow-clear />
<a-tree :treeData="treeData"
:selectedKeys.sync="selectKeys"
@expand="onExpand"
:expanded-keys="expandedKeys"
:auto-expand-parent="autoExpandParent">
<template slot-scope="item"
class="item-content">
<span>{{ item }}</span>
</template>
</a-tree>
data () {
return {
treeData: [],//树的data
selectKeys: [],
searchStr: '',
expandedKeys: [],
autoExpandParent: true
}
},
methods: {
handleNodeClick (keys, event) {
this.$emit('select', event.node.dataRef)
},
onExpand (expandedKeys) {
console.log(expandedKeys, 'expandedKeys')
this.expandedKeys = expandedKeys
this.autoExpandParent = false
},
onSearch (e) {
if (e === '') {
this.getDeptTree()
return
}
if (e === this.searchStr) { //避免重复搜索
return
}
const newData = JSON.parse(JSON.stringify(this.treeData))
const allKey = this.getkeyList(e, newData, [])
if (allKey.length > 0) { //有数据赋值,再将父节点展开
newData[0].children = []
newData[0].children = allKey
this.treeData = newData
this.onExpand([this.treeData[0].deptId])
} else {
return this.$notification['info']({ message: '没有找到" ' + e + ' "的部门' })
}
},
getkeyList (value, tree, keyList) { //递归调用
this.searchStr = value
// 遍历所有同一级的树
for (let i = 0; i < tree.length; i++) {
const node = tree[i]
// 如果该节点存在value值则push
if (node.deptName.indexOf(value) !== -1) {
keyList.push(node)
}
// 如果拥有孩子继续遍历
if (node.children.length > 0) {
this.getkeyList(value, node.children, keyList)
}
}
// 因为是引用类型,所有每次递归操作的都是同一个数组
return keyList
}
}