vue实现搜索高亮
实现搜索高亮的方法
在Vue中实现搜索高亮可以通过多种方式完成,以下是几种常见的实现方法:
使用v-html和正则表达式
通过正则表达式匹配搜索关键词,并用HTML标签包裹匹配到的内容,最后使用v-html渲染结果。
<template>
<div>
<input v-model="searchText" placeholder="输入搜索内容" />
<div v-html="highlightedText"></div>
</div>
</template>
<script>
export default {
data() {
return {
originalText: '这是一段需要高亮显示的文本内容',
searchText: ''
}
},
computed: {
highlightedText() {
if (!this.searchText) return this.originalText
const regex = new RegExp(this.searchText, 'gi')
return this.originalText.replace(regex, match =>
`<span style="background-color: yellow">${match}</span>`
)
}
}
}
</script>
使用自定义指令
创建自定义指令来处理文本高亮,使代码更模块化和可复用。
Vue.directive('highlight', {
inserted(el, binding) {
const text = el.textContent
const searchText = binding.value
if (!searchText) return
const regex = new RegExp(searchText, 'gi')
el.innerHTML = text.replace(regex, match =>
`<span style="background-color: yellow">${match}</span>`
)
},
update(el, binding) {
const text = el.textContent
const searchText = binding.value
const regex = new RegExp(searchText, 'gi')
el.innerHTML = text.replace(regex, match =>
`<span style="background-color: yellow">${match}</span>`
)
}
})
使用组件封装
创建一个专门的高亮组件,接收原始文本和搜索词作为props。
<template>
<span>
<template v-for="(part, index) in parts">
<span
v-if="part.highlight"
:key="index"
style="background-color: yellow"
>
{{ part.text }}
</span>
<span v-else :key="index">
{{ part.text }}
</span>
</template>
</span>
</template>
<script>
export default {
props: {
text: String,
search: String
},
computed: {
parts() {
if (!this.search) return [{ text: this.text, highlight: false }]
const regex = new RegExp(this.search, 'gi')
const matches = [...this.text.matchAll(regex)]
if (matches.length === 0) return [{ text: this.text, highlight: false }]
let lastIndex = 0
const parts = []
matches.forEach(match => {
const index = match.index
if (index > lastIndex) {
parts.push({
text: this.text.substring(lastIndex, index),
highlight: false
})
}
parts.push({
text: match[0],
highlight: true
})
lastIndex = index + match[0].length
})
if (lastIndex < this.text.length) {
parts.push({
text: this.text.substring(lastIndex),
highlight: false
})
}
return parts
}
}
}
</script>
注意事项
使用v-html时需要注意XSS攻击风险,确保搜索内容来自可信来源或进行适当转义。
高亮实现应考虑性能问题,特别是处理大量文本时,可以使用防抖技术优化搜索输入处理。
对于复杂搜索需求,可能需要更高级的正则表达式或分词处理来改善匹配效果。







