vue实现搜索高亮
实现搜索高亮的方法
在Vue中实现搜索高亮可以通过以下步骤完成,结合字符串处理和动态样式绑定。

使用字符串替换与v-html
通过将匹配的搜索词替换为带有高亮样式的HTML标签,再使用v-html渲染内容。需注意防范XSS攻击。

<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 style="background-color: yellow;">${match}</span>`
);
}
}
};
</script>
使用自定义指令
封装一个自定义指令v-highlight,实现更灵活的高亮逻辑。
<template>
<div>
<input v-model="searchText" />
<div v-highlight="searchText" style="background-color: yellow;">
这里是需要被高亮的文本内容
</div>
</div>
</template>
<script>
export default {
directives: {
highlight(el, binding) {
const text = el.textContent;
const searchText = binding.value;
if (!searchText) {
el.innerHTML = text;
return;
}
const regex = new RegExp(searchText, 'gi');
el.innerHTML = text.replace(regex, match =>
`<span style="background-color: yellow;">${match}</span>`
);
}
},
data() {
return { searchText: "" };
}
};
</script>
结合第三方库
使用如mark.js等库简化高亮逻辑,适合复杂场景。
npm install mark.js
<template>
<div>
<input v-model="searchText" />
<div ref="content">
这里是需要被高亮的文本内容
</div>
</div>
</template>
<script>
import Mark from 'mark.js';
export default {
data() {
return { searchText: "" };
},
watch: {
searchText(newVal) {
const mark = new Mark(this.$refs.content);
mark.unmark();
if (newVal) mark.mark(newVal);
}
}
};
</script>
注意事项
- XSS防护:使用
v-html时确保内容可信,或通过库如DOMPurify过滤。 - 性能优化:大数据量时考虑防抖(如
lodash.debounce)减少频繁渲染。 - 样式定制:通过CSS类替代内联样式,便于统一管理。
以上方法可根据项目需求选择,平衡灵活性与维护性。






