vue实现搜索变色
实现搜索关键词高亮的基本思路
在Vue中实现搜索关键词高亮,主要通过以下步骤完成:
- 获取用户输入的搜索关键词
- 遍历需要高亮的内容
- 使用正则表达式匹配关键词
- 将匹配到的关键词替换为带有高亮样式的HTML元素
基础实现方法
<template>
<div>
<input v-model="searchText" placeholder="输入搜索关键词" />
<div v-html="highlightedContent"></div>
</div>
</template>
<script>
export default {
data() {
return {
searchText: '',
originalContent: '这是一段需要搜索高亮的文本内容'
}
},
computed: {
highlightedContent() {
if (!this.searchText) return this.originalContent
const regex = new RegExp(this.searchText, 'gi')
return this.originalContent.replace(
regex,
match => `<span class="highlight">${match}</span>`
)
}
}
}
</script>
<style>
.highlight {
background-color: yellow;
color: black;
}
</style>
处理特殊字符的正则表达式
为了避免搜索内容中包含正则特殊字符导致错误,需要对输入进行转义:

function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
}
// 在highlightedContent计算属性中使用
const escapedSearchText = escapeRegExp(this.searchText)
const regex = new RegExp(escapedSearchText, 'gi')
多关键词高亮实现
如果需要同时高亮多个关键词,可以扩展实现:
computed: {
highlightedContent() {
let result = this.originalContent
if (!this.searchText) return result
const keywords = this.searchText.split(' ').filter(k => k.trim())
keywords.forEach(keyword => {
const escaped = escapeRegExp(keyword)
const regex = new RegExp(escaped, 'gi')
result = result.replace(
regex,
match => `<span class="highlight">${match}</span>`
)
})
return result
}
}
列表项高亮实现
对于列表数据的高亮处理:

<template>
<div>
<input v-model="searchText" />
<ul>
<li v-for="(item, index) in filteredList" :key="index" v-html="item.highlighted"></li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
searchText: '',
items: [
{ text: 'Vue.js框架' },
{ text: 'React框架' },
{ text: 'Angular框架' }
]
}
},
computed: {
filteredList() {
return this.items.map(item => {
if (!this.searchText) {
return { ...item, highlighted: item.text }
}
const escaped = escapeRegExp(this.searchText)
const regex = new RegExp(escaped, 'gi')
const highlighted = item.text.replace(
regex,
match => `<span class="highlight">${match}</span>`
)
return { ...item, highlighted }
})
}
}
}
</script>
性能优化建议
对于大数据量的高亮处理,可以考虑以下优化:
- 使用防抖处理搜索输入
- 虚拟滚动只渲染可见区域的内容
- 避免频繁的正则表达式创建
import { debounce } from 'lodash'
export default {
data() {
return {
searchText: '',
debouncedSearchText: ''
}
},
created() {
this.debouncedUpdateSearchText = debounce(function(text) {
this.debouncedSearchText = text
}, 300)
},
watch: {
searchText(newVal) {
this.debouncedUpdateSearchText(newVal)
}
},
computed: {
// 使用debouncedSearchText替代searchText
}
}
安全注意事项
使用v-html时需要注意XSS攻击风险,确保:
- 只对可信内容使用v-html
- 对用户输入进行适当的转义处理
- 考虑使用DOMPurify等库净化HTML
import DOMPurify from 'dompurify'
// 在高亮函数中使用
return DOMPurify.sanitize(originalContent.replace(regex, ...))
以上实现方法可以根据具体需求进行调整和扩展,核心思路是通过正则匹配和HTML替换实现关键词高亮效果。






