vue实现搜索变色
实现搜索关键词高亮的方法
在Vue中实现搜索关键词高亮显示,可以通过自定义指令或过滤器实现。以下是两种常见实现方式:
方法一:使用v-html指令
创建一个方法处理文本并替换关键词:

methods: {
highlight(text, keyword) {
if (!keyword) return text
const regex = new RegExp(keyword, 'gi')
return text.replace(regex, match => `<span class="highlight">${match}</span>`)
}
}
在模板中使用:
<div v-html="highlight(content, searchKeyword)"></div>
方法二:自定义指令

注册全局指令:
Vue.directive('highlight', {
inserted(el, binding) {
const { value, arg } = binding
if (!arg) return
const regex = new RegExp(arg, 'gi')
el.innerHTML = value.replace(regex, match =>
`<span style="background-color: yellow;">${match}</span>`
)
}
})
使用指令:
<div v-highlight:keyword="content"></div>
样式处理
添加CSS样式控制高亮效果:
.highlight {
background-color: yellow;
font-weight: bold;
color: #333;
}
注意事项
- 使用v-html时需注意XSS攻击风险,确保内容可信
- 复杂匹配场景可考虑使用第三方库如mark.js
- 性能优化:大量文本处理时建议使用虚拟滚动
完整组件示例
<template>
<div>
<input v-model="keyword" placeholder="输入关键词"/>
<div v-html="highlightedText"></div>
</div>
</template>
<script>
export default {
data() {
return {
keyword: '',
originalText: '这是一段需要搜索高亮的示例文本'
}
},
computed: {
highlightedText() {
return this.highlight(this.originalText, this.keyword)
}
},
methods: {
highlight(text, keyword) {
if (!keyword) return text
const regex = new RegExp(keyword.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi')
return text.replace(regex, match => `<span class="highlight">${match}</span>`)
}
}
}
</script>






