vue实现搜索高亮
Vue 实现搜索高亮的方法
使用 v-html 和字符串替换
通过字符串替换将匹配的搜索词包裹在高亮标签(如 <span class="highlight">)中,再通过 v-html 渲染。
<template>
<div>
<input v-model="searchText" placeholder="输入搜索词">
<div v-html="highlightedContent"></div>
</div>
</template>
<script>
export default {
data() {
return {
content: "这里是需要高亮显示的文本内容",
searchText: ""
};
},
computed: {
highlightedContent() {
if (!this.searchText) return this.content;
const regex = new RegExp(this.searchText, "gi");
return this.content.replace(regex, match =>
`<span class="highlight">${match}</span>`
);
}
}
};
</script>
<style>
.highlight {
background-color: yellow;
font-weight: bold;
}
</style>
使用自定义指令
通过自定义指令 v-highlight 动态处理文本节点的高亮逻辑。
<template>
<div>
<input v-model="searchText" placeholder="输入搜索词">
<div v-highlight="searchText">{{ content }}</div>
</div>
</template>
<script>
export default {
data() {
return {
content: "这里是需要高亮显示的文本内容",
searchText: ""
};
},
directives: {
highlight: {
inserted(el, binding) {
const text = el.textContent;
if (!binding.value) return;
const regex = new RegExp(binding.value, "gi");
el.innerHTML = text.replace(regex, match =>
`<span class="highlight">${match}</span>`
);
},
update(el, binding) {
const text = el.textContent;
if (!binding.value) {
el.innerHTML = text;
return;
}
const regex = new RegExp(binding.value, "gi");
el.innerHTML = text.replace(regex, match =>
`<span class="highlight">${match}</span>`
);
}
}
}
};
</script>
使用第三方库
借助第三方库如 mark.js 实现更复杂的高亮功能(如多词高亮、分词组匹配等)。
<template>
<div>
<input v-model="searchText" placeholder="输入搜索词">
<div ref="content">{{ content }}</div>
</div>
</template>
<script>
import Mark from "mark.js";
export default {
data() {
return {
content: "这里是需要高亮显示的文本内容",
searchText: ""
};
},
watch: {
searchText(newVal) {
const markInstance = new Mark(this.$refs.content);
markInstance.unmark();
if (newVal) markInstance.mark(newVal);
}
}
};
</script>
动态样式与性能优化
对于长文本或频繁更新的场景,可以通过以下方式优化性能:

- 使用
debounce延迟搜索触发。 - 避免直接操作 DOM,优先使用虚拟滚动(如
vue-virtual-scroller)。
<template>
<div>
<input
v-model="searchText"
placeholder="输入搜索词"
@input="debouncedHighlight"
>
<div v-html="highlightedContent"></div>
</div>
</template>
<script>
import { debounce } from "lodash";
export default {
data() {
return {
content: "长文本内容...",
searchText: "",
debouncedHighlight: debounce(function() {}, 300)
};
},
methods: {
highlight() {
// 高亮逻辑
}
},
created() {
this.debouncedHighlight = debounce(this.highlight, 300);
}
};
</script>
注意事项
- XSS 防护:使用
v-html时需确保内容可信,避免注入攻击。 - 大小写敏感:通过正则表达式参数(如
gi)控制是否忽略大小写。 - 多词高亮:可通过拆分搜索词为数组,循环处理匹配逻辑。






