vue实现搜索高亮显示
实现搜索高亮的基本思路
在Vue中实现搜索高亮的核心是通过正则表达式匹配关键词,并将匹配到的内容用HTML标签(如<span class="highlight">)包裹,最后通过v-html渲染处理后的文本。需注意安全性问题,避免XSS攻击。
方法一:使用计算属性处理高亮
定义一个计算属性,将原始文本中的关键词替换为高亮样式:
<template>
<div>
<input v-model="searchText" placeholder="输入搜索词" />
<div v-html="highlightedContent"></div>
</div>
</template>
<script>
export default {
data() {
return {
content: "这里是需要高亮显示的文本内容,包含Vue和JavaScript关键词。",
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-html时需确保内容来源可信,避免XSS攻击。 - 正则表达式中的
gi表示全局匹配且忽略大小写。
方法二:封装高亮为全局指令
将高亮逻辑封装为Vue自定义指令,方便复用:
// main.js 或单独指令文件
Vue.directive('highlight', {
bind(el, binding) {
const text = el.textContent;
const search = binding.value;
if (!search) return;
const regex = new RegExp(search, 'gi');
el.innerHTML = text.replace(
regex,
match => `<span class="highlight">${match}</span>`
);
},
update(el, binding) {
// 搜索词变化时重新渲染
const text = el.textContent;
const search = binding.value;
if (!search) {
el.innerHTML = text;
return;
}
const regex = new RegExp(search, 'gi');
el.innerHTML = text.replace(
regex,
match => `<span class="highlight">${match}</span>`
);
}
});
// 组件中使用
<template>
<div v-highlight="searchText">{{ content }}</div>
</template>
方法三:处理多关键词高亮
若需支持多个关键词高亮,可通过拆分搜索词并循环处理:

computed: {
highlightedContent() {
if (!this.searchText) return this.content;
const keywords = this.searchText.split(' ').filter(k => k.trim());
let result = this.content;
keywords.forEach(keyword => {
const regex = new RegExp(keyword, 'gi');
result = result.replace(
regex,
match => `<span class="highlight">${match}</span>`
);
});
return result;
}
}
安全增强建议
若内容可能包含用户输入,建议使用DOMPurify库过滤HTML:
npm install dompurify
import DOMPurify from 'dompurify';
computed: {
highlightedContent() {
const rawHtml = this.replaceKeywords(); // 替换逻辑
return DOMPurify.sanitize(rawHtml);
}
}
性能优化
对于长文本或高频搜索,可通过防抖(debounce)减少计算次数:
import { debounce } from 'lodash';
methods: {
updateHighlight: debounce(function() {
this.highlightedContent = this.calculateHighlight();
}, 300)
}






