1.使用v-html来对搜索出来的内容进行渲染
<vxe-column field="name" title="菜单名称" tree-node show-overflow="title">
<template #default="{ row }">
<div class="ellipsis">
<i :class="'iconfont ' + row.icon"></i>
<span v-html="getRenderer(row.name)"></span>
</div>
</template>
</vxe-column>
<vxe-column field="key" title="关键字" show-overflow="title">
<template #default="{ row }">
<div class="ellipsis">
<span v-html="getRenderer(row.key)"></span>
</div>
</template>
</vxe-column>
2.匹配当前搜索框的关键词
getRenderer(name) {
let renderValue = name;
if (this.keyWord) {
renderValue = name.replaceAll(
this.keyWord,
'<span style="background:yellow" class="hightText">' + this.keyWord + '</span>'
);
}
return renderValue;
},
3.在搜索框中输入搜索关键词
<div class="flex-align-center">
<el-input
v-model="keyWord"
size="small"
@input="handleInput"
@keyup.enter.native="handleSearch"
placeholder="请输入菜单关键字"
></el-input>
<i class="iconfont icon-sousu ml-5 pointer" @click="handleSearch"></i>
<i class="iconfont icon-shuaxin ml-5 pointer" @click="handleInitData"></i>
</div>
4.处理高亮和按下enter键后回车
handleInput() {
if (this.keyWord) {
this.$refs.xTree.setAllTreeExpand(true);
}
this.searchhead = 0;
},
handleSearch() {
//展开全部
this.$refs.xTree.setAllTreeExpand(true);
let num = document.getElementsByClassName('hightText').length;
if (num != 0) {
//如果查询关键词存在,跳到第一个关键词的位置,标头增1,走满一圈归0
document.getElementsByClassName('hightText')[this.searchhead].scrollIntoView();
document.getElementsByClassName('hightText')[this.searchhead].outerHTML =
'<span style="background:red;" class="hightText">' + this.keyWord + '</span>';
if (this.searchhead < num - 1) {
this.searchhead += 1;
} else if (this.searchhead == num - 1) {
this.searchhead = 0;
}
}
}
5.data中的数据
searchhead: 0,
keyWord: '', //菜单搜索的关键字