vue实现高亮
Vue实现文本高亮的几种方法
在Vue中实现文本高亮可以通过多种方式完成,以下是几种常见的方法:
使用v-html指令
通过将需要高亮的文本替换为HTML标签,再使用v-html渲染:
<template>
<div v-html="highlightedText"></div>
</template>
<script>
export default {
data() {
return {
originalText: '这是一个需要高亮的文本',
keyword: '高亮'
}
},
computed: {
highlightedText() {
const regex = new RegExp(this.keyword, '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 keyword = binding.value
const regex = new RegExp(keyword, 'gi')
el.innerHTML = text.replace(regex, match =>
`<span style="background-color: yellow">${match}</span>`
)
}
})
// 使用方式
<template>
<div v-highlight="keyword">{{ originalText }}</div>
</template>
使用组件封装
创建一个专门的高亮组件,更易于维护:
<template>
<span>
<template v-for="(part, index) in parts">
<span v-if="part.highlight" :key="index" class="highlight">
{{ part.text }}
</span>
<span v-else :key="index">
{{ part.text }}
</span>
</template>
</span>
</template>
<script>
export default {
props: {
text: String,
keyword: String
},
computed: {
parts() {
if (!this.keyword) return [{ text: this.text, highlight: false }]
const regex = new RegExp(this.keyword, 'gi')
const parts = []
let lastIndex = 0
let match
while ((match = regex.exec(this.text)) !== null) {
if (match.index > lastIndex) {
parts.push({
text: this.text.slice(lastIndex, match.index),
highlight: false
})
}
parts.push({
text: match[0],
highlight: true
})
lastIndex = match.index + match[0].length
}
if (lastIndex < this.text.length) {
parts.push({
text: this.text.slice(lastIndex),
highlight: false
})
}
return parts
}
}
}
</script>
<style>
.highlight {
background-color: yellow;
}
</style>
使用第三方库
可以使用专门的高亮库如mark.js:
npm install mark.js
// 组件中使用
<template>
<div ref="content">
{{ content }}
</div>
</template>
<script>
import Mark from 'mark.js'
export default {
data() {
return {
content: '需要高亮的文本内容',
keyword: '高亮'
}
},
watch: {
keyword(newVal) {
this.highlightText(newVal)
}
},
methods: {
highlightText(keyword) {
const instance = new Mark(this.$refs.content)
instance.unmark()
if (keyword) {
instance.mark(keyword, {
className: 'highlight'
})
}
}
},
mounted() {
this.highlightText(this.keyword)
}
}
</script>
性能优化建议
对于大量文本的高亮操作,建议使用虚拟滚动或分页加载技术,避免一次性处理过多DOM节点影响性能。
动态高亮时,使用防抖或节流技术减少高频操作带来的性能开销:

import { debounce } from 'lodash'
methods: {
highlightText: debounce(function(keyword) {
// 高亮逻辑
}, 300)
}
安全注意事项
使用v-html时要特别注意XSS攻击风险,确保高亮的内容来自可信源,或对输入内容进行适当的转义和过滤。






