需求:基于element的tree组件,过滤搜索时支持多个关键字搜索,以空格隔开,比如搜索“今天 下雨”,那么就是name中含有“今天”和“下雨”的关键字就要显示并且“今天”和“下雨”的关键字要变红色。
<template>
<div>
<el-input placeholder="输入关键字进行过滤" v-model="filterText"> </el-input>
<el-tree
class="filter-tree"
:data="data"
:props="defaultProps"
default-expand-all
:filter-node-method="filterNode"
ref="tree"
>
</el-tree>
</div>
</template>
<script>
export default {
watch: {
filterText(val) {
this.$refs.tree.filter(val);
this.$nextTick(() => {
this.setSearchStyle(val);
});
},
},
methods: {
// 去色
delSearchStyle() {
let arr = document.querySelectorAll(
".filter-tree .el-tree-node__children div.el-tree-node.is-expanded.is-focusable .el-tree-node__label"
);
for (let i = 0; i < arr.length; i++) {
let values = arr[i].innerHTML;
arr[i].innerHTML = values
.split('<font style="color: red;">')
.join("")
.split("</font>")
.join("");
}
},
// 上色
setSearchStyle(val) {
this.delSearchStyle();
let vallist = val.split(" ");
let arr = document.querySelectorAll(
".filter-tree .el-tree-node__children div:not(.is-hidden).el-tree-node.is-expanded.is-focusable .el-tree-node__label"
);
for (let i = 0; i < arr.length; i++) {
for (let v of vallist) {
if (v === "") continue; //这里是为了处理当输入空格隔开时的场景
if (arr[i].innerText.indexOf(v) !== -1) {
let reg = new RegExp(v, "g");
arr[i].innerHTML = arr[i].innerHTML.replace(
reg,
`<font style="color: red;">${v}</font>`
);
}
}
}
},
filterNode(value, data) {
if (!value) return true;
let arr = value.split(" "); //用空格将关键字打散成数组
return arr.every((item) => data.label.indexOf(item) !== -1); //这里是满足关键字同时出现在一个label中的逻辑
},
},
data() {
return {
filterText: "",
data: [
{
id: 1,
label: "一级 1",
children: [
{
id: 4,
label: "二级 1-1",
children: [
{
id: 9,
label: "三级 1-1-1",
},
{
id: 10,
label: "三级 1-1-2",
},
],
},
],
},
{
id: 2,
label: "一级 2",
children: [
{
id: 5,
label: "二级 2-1",
},
{
id: 6,
label: "二级 2-2",
},
],
},
{
id: 3,
label: "一级 3",
children: [
{
id: 7,
label: "二级 3-1",
},
{
id: 8,
label: "二级 3-2",
},
],
},
],
defaultProps: {
children: "children",
label: "label",
},
};
},
};
</script>
————————————————
版权声明:本文为CSDN博主「人间不值得丶丶丶」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/Machangzhi_1115/article/details/116015481