vue实现搜索变色
实现搜索关键词高亮的方法
在Vue中实现搜索关键词高亮显示,可以通过以下方式实现:
使用v-html指令
<template>
<div>
<input v-model="searchText" placeholder="输入搜索关键词">
<div v-html="highlightText(originalText)"></div>
</div>
</template>
<script>
export default {
data() {
return {
originalText: '这是一段需要高亮显示的文本内容',
searchText: ''
}
},
methods: {
highlightText(text) {
if (!this.searchText) return text
const regex = new RegExp(this.searchText, 'gi')
return text.replace(regex, match =>
`<span style="background-color: yellow">${match}</span>`
)
}
}
}
</script>
使用计算属性优化
computed: {
highlightedContent() {
const searchTerm = this.searchText.trim()
if (!searchTerm) return this.originalText
const regex = new RegExp(searchTerm, 'gi')
return this.originalText.replace(regex,
match => `<span class="highlight">${match}</span>`
)
}
}
添加CSS样式
.highlight {
background-color: yellow;
font-weight: bold;
color: #333;
}
安全注意事项
使用v-html时需注意XSS攻击风险,应对输入内容进行转义处理:
methods: {
escapeHtml(unsafe) {
return unsafe
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'")
},
highlightText(text) {
const safeText = this.escapeHtml(text)
const safeSearch = this.escapeHtml(this.searchText)
// ...后续高亮逻辑
}
}
支持多关键词高亮
如需支持多个关键词高亮显示:
highlightText(text) {
if (!this.searchText) return text
const keywords = this.searchText.split(' ').filter(k => k)
let result = text
keywords.forEach(keyword => {
const regex = new RegExp(keyword, 'gi')
result = result.replace(regex,
match => `<span class="highlight">${match}</span>`
)
})
return result
}
性能优化建议
对于大量文本内容,考虑使用虚拟滚动技术或分页显示,避免一次性处理过多DOM节点导致性能问题。







