1. 主要思路:
- 監(jiān)聽輸入框內(nèi)容,過濾
treeData,僅保留匹配項及其父級。 - 在
title渲染時,高亮匹配部分的文本。
2. 代碼實現(xiàn):
<template>
<div>
<a-input v-model="searchValue" placeholder="請輸入關(guān)鍵字" @input="onSearch" style="margin-bottom: 10px;" />
<a-tree
:tree-data="expandedTreeData"
:expanded-keys="expandedKeys"
:auto-expand-parent="autoExpandParent"
>
<template #title="{ title }">
<span v-html="getHighlightedText(title)"></span>
</template>
</a-tree>
</div>
</template>
<script>
export default {
data() {
return {
searchValue: "",
expandedKeys: [],
autoExpandParent: true,
treeData: [
{
title: "一級 1",
key: "0-1",
children: [
{ title: "二級 1-1", key: "0-1-1" },
{ title: "二級 1-2", key: "0-1-2" }
]
},
{
title: "一級 2",
key: "0-2",
children: [
{ title: "二級 2-1", key: "0-2-1" },
{ title: "二級 2-2", key: "0-2-2" }
]
}
],
expandedTreeData: []
};
},
created() {
this.expandedTreeData = this.treeData;
},
methods: {
onSearch() {
const searchValue = this.searchValue.trim();
if (!searchValue) {
this.expandedTreeData = this.treeData;
this.expandedKeys = [];
return;
}
const expandedKeys = [];
const filterTreeData = (data) => {
return data
.map((item) => {
const titleMatch = item.title.includes(searchValue);
if (titleMatch) expandedKeys.push(item.key);
if (item.children) {
const filteredChildren = filterTreeData(item.children);
if (filteredChildren.length || titleMatch) {
return { ...item, children: filteredChildren };
}
}
return titleMatch ? item : null;
})
.filter(Boolean);
};
this.expandedTreeData = filterTreeData(this.treeData);
this.expandedKeys = expandedKeys;
this.autoExpandParent = true;
},
getHighlightedText(text) {
if (!this.searchValue) return text;
const regex = new RegExp(`(${this.searchValue})`, "gi");
return text.replace(regex, `<span style="color: red;">$1</span>`);
}
}
};
</script>
3. 關(guān)鍵點解析:
-
搜索邏輯
- 遍歷
treeData,找到匹配項及其父級節(jié)點。 - 只保留符合搜索條件的節(jié)點及路徑上的所有父級節(jié)點。
- 遍歷
-
高亮匹配文本
- 使用
v-html直接渲染高亮部分。 - 用正則表達式替換匹配部分,添加
span并改變顏色。
- 使用
-
自動展開搜索結(jié)果
- 記錄搜索到的節(jié)點
key并賦值給expandedKeys,以展開相關(guān)節(jié)點。
- 記錄搜索到的節(jié)點
效果:
- 輸入關(guān)鍵詞,樹狀結(jié)構(gòu)自動篩選,并展開包含匹配項的所有父級節(jié)點。
- 匹配文本部分變紅色高亮。
這個方案兼顧了搜索、匹配高亮、自動展開父級,符合 a-tree 組件的常見需求。 ??