参考antd组件 https://www.antdv.com/components/tree-cn#components-tree-demo-search
1.组件结构代码
<a-input placeholder="按enter键搜索" v-model:value="searchValue" />
<a-tree :tree-data="list" :expanded-keys="expandedKeys" :auto-expand-parent="autoExpandParent" @expand="onExpand">
<template #title="{ title }">
<span v-if="title.indexOf(searchValue) > -1">
{{ title.substr(0, title.indexOf(searchValue)) }}
<span style="color: #f50">{{ searchValue }}</span>
{{ title.substr(title.indexOf(searchValue) + searchValue.length) }}
</span>
<span v-else>{{ title }}</span>
</template>
</tree>
<script>
import { ref, watch } from 'vue';
setup (props, context) {
const list = ref([
{
key: 1,
title: '团队一',
children: [
{
key: 22,
title: '研发',
children: [
{
key: 23,
title: '张三',
icon: 1
}
]
},
]
},
])
//展开的key
const expandedKeys = ref([])
//搜索关键字
const searchValue = ref('');
//是否展开树
const autoExpandParent = ref(true);
// 展开收起触发
const onExpand = keys => {
expandedKeys.value = keys;
autoExpandParent.value = false;
}
//处理数据,拿到 提取 key title 格式为 :{key:key,title: node.title } Antd组件方法
const dataList = [];
const generateList = data => {
for (let i = 0; i < data.length; i++) {
const node = data[i];
const key = node.key;
console.log('node', node);
dataList.push({
key,
title: node.title,
});
if (node.children) {
generateList(node.children);
}
}
};
generateList(list.value);
//andt 组件方法 获取父级节点key
const getParentKey = (key, tree) => {
let parentKey;
for (let i = 0; i < tree.length; i++) {
const node = tree[i];
if (node.children) {
if (node.children.some(item => item.key === key)) {
parentKey = node.key;
} else if (getParentKey(key, node.children)) {
parentKey = getParentKey(key, node.children);
}
}
}
return parentKey;
};
//搜索事件
watch(searchValue, value => {
if (!value) return autoExpandParent.value = false;
const expanded = dataList.map(item => {
if (item.title.indexOf(value) > -1) {
return getParentKey(item.key, list.value);
}
return null;
}).filter((item, i, self) => item && self.indexOf(item) === i);
expandedKeys.value = expanded;
searchValue.value = value;
autoExpandParent.value = true;
});
}
</script>