vue实现搜索高亮显示
实现搜索高亮的基本思路
在Vue中实现搜索高亮的核心逻辑是通过正则表达式匹配关键词,并将匹配到的内容替换为带有高亮样式的HTML标签(如<span class="highlight">)。需要结合Vue的数据绑定和动态渲染特性。
定义高亮样式
在CSS中定义高亮样式,例如:
.highlight {
background-color: yellow;
color: black;
font-weight: bold;
}
创建高亮方法
在Vue组件中定义一个方法,用于处理文本并返回高亮后的HTML字符串:

methods: {
highlightText(text, keyword) {
if (!keyword) return text;
const regex = new RegExp(keyword, 'gi');
return text.replace(regex, match => `<span class="highlight">${match}</span>`);
}
}
模板中使用高亮
在模板中通过v-html指令渲染高亮后的内容(注意防范XSS风险):
<template>
<div>
<input v-model="searchKeyword" placeholder="输入搜索关键词" />
<div v-html="highlightText(originalText, searchKeyword)"></div>
</div>
</template>
处理多关键词高亮
若需支持多关键词高亮,可扩展高亮方法:

highlightText(text, keywords) {
if (!keywords) return text;
const keywordArray = keywords.split(' ');
let result = text;
keywordArray.forEach(keyword => {
if (keyword) {
const regex = new RegExp(keyword, 'gi');
result = result.replace(regex, match => `<span class="highlight">${match}</span>`);
}
});
return result;
}
安全性注意事项
使用v-html时需确保内容可信,避免XSS攻击。可通过DOMPurify等库过滤危险内容:
import DOMPurify from 'dompurify';
// ...
highlightText(text, keyword) {
const highlighted = /* 高亮逻辑 */;
return DOMPurify.sanitize(highlighted);
}
性能优化建议
对于大量文本的高亮操作,可通过以下方式优化:
- 使用防抖(debounce)延迟高亮计算
- 避免在每次输入时重新处理整个文本
- 考虑虚拟滚动技术处理长列表
完整组件示例
<template>
<div>
<input v-model="searchKeyword" placeholder="输入搜索关键词" />
<div v-html="safeHighlightedText"></div>
</div>
</template>
<script>
import DOMPurify from 'dompurify';
export default {
data() {
return {
originalText: '这是一段需要高亮显示的示例文本,包含多个关键词。',
searchKeyword: ''
};
},
computed: {
safeHighlightedText() {
return DOMPurify.sanitize(this.highlightText(this.originalText, this.searchKeyword));
}
},
methods: {
highlightText(text, keyword) {
if (!keyword) return text;
const regex = new RegExp(keyword, 'gi');
return text.replace(regex, match => `<span class="highlight">${match}</span>`);
}
}
};
</script>
<style>
.highlight {
background-color: yellow;
}
</style>






