vxe-tree vue 樹組件實現(xiàn)關(guān)鍵字搜索
vxe-tree vue 樹組件實現(xiàn)關(guān)鍵字搜索
查看官網(wǎng):https://vxeui.com
gitbub:https://github.com/x-extends/vxe-pc-ui
gitee:https://gitee.com/x-extends/vxe-pc-ui

代碼
實現(xiàn)方式通過輸入框輸入內(nèi)容,對數(shù)據(jù)進(jìn)行篩選過濾
<template>
<div>
<div>
<vxe-input v-model="filterName" type="search" clearable @change="searchEvent"></vxe-input>
</div>
<vxe-tree ref="treeRef" class="mytree-list" v-bind="treeOptions">
<template #title="{ node }">
<span v-html="node.title"></span>
</template>
</vxe-tree>
</div>
</template>
<script setup>
import { ref, reactive, nextTick } from 'vue'
import XEUtils from 'xe-utils'
const treeRef = ref()
const allData = [
{ title: '節(jié)點2', id: '2' },
{
title: '節(jié)點3',
id: '3',
children: [
{ title: '節(jié)點3-1', id: '31' },
{
title: '節(jié)點3-2',
id: '32',
children: [
{ title: '節(jié)點3-2-1', id: '321' },
{ title: '節(jié)點3-2-2', id: '322' }
]
},
{
title: '節(jié)點3-3',
id: '33',
children: [
{ title: '節(jié)點3-3-1', id: '331' },
{ title: '節(jié)點3-3-2', id: '332' },
{ title: '節(jié)點3-3-3', id: '333' }
]
},
{ title: '節(jié)點3-4', id: '34' }
]
},
{
title: '節(jié)點4',
id: '4',
children: [
{
title: '節(jié)點4-1',
id: '41',
children: [
{ title: '節(jié)點4-1-1', id: '411' },
{ title: '節(jié)點4-1-2', id: '412' }
]
},
{ title: '節(jié)點4-2', id: '42' },
{
title: '節(jié)點4-3',
id: '43',
children: [
{ title: '節(jié)點4-3-1', id: '431' },
{ title: '節(jié)點4-3-2', id: '432' }
]
}
]
},
{ title: '節(jié)點5', id: '5' }
]
const filterName = ref('')
const treeOptions = reactive({
childrenField: 'childList',
data: []
})
const handleSearch = () => {
const filterVal = XEUtils.toValueString(filterName.value).trim().toLowerCase()
if (filterVal) {
const filterRE = new RegExp(filterVal, 'gi')
const rest = XEUtils.searchTree(allData, item => {
return String(item.title).toLowerCase().indexOf(filterVal) > -1
}, { children: 'children', mapChildren: 'childList', isEvery: true })
XEUtils.eachTree(rest, item => {
item.title = String(item.title).replace(filterRE, match => `<span class="keyword-highlight">${match}</span>`)
}, { children: 'childList' })
treeOptions.data = rest
} else {
const rest = XEUtils.searchTree(allData, () => true, { children: 'children', mapChildren: 'childList', isEvery: true })
treeOptions.data = rest
}
// 搜索之后默認(rèn)展開所有子節(jié)點。清除搜索之后默認(rèn)收起所有子節(jié)點
nextTick(() => {
const $tree = treeRef.value
if ($tree) {
$tree.setAllExpandNode(!!filterVal)
}
})
}
// 節(jié)流函數(shù),間隔500毫秒觸發(fā)搜索
const searchEvent = XEUtils.throttle(function () {
handleSearch()
}, 500, { trailing: true, leading: true })
handleSearch()
</script>
<style lang="scss" scoped>
.mytree-list {
::v-deep(.keyword-highlight) {
background-color: #FFFF00;
}
}
</style>

浙公網(wǎng)安備 33010602011771號