vue实现高亮显示
Vue 实现高亮显示的方法
使用 v-html 指令
在 Vue 中可以使用 v-html 指令动态渲染 HTML 内容。通过将需要高亮的文本替换为带有样式标签的字符串,可以实现高亮效果。
<template>
<div v-html="highlightedText"></div>
</template>
<script>
export default {
data() {
return {
originalText: 'This is some text with keywords to highlight',
keyword: 'keywords'
}
},
computed: {
highlightedText() {
return this.originalText.replace(
new RegExp(this.keyword, 'gi'),
match => `<span style="background-color: yellow">${match}</span>`
)
}
}
}
</script>
使用自定义指令
可以创建一个自定义指令专门处理文本高亮逻辑,使代码更模块化。
<template>
<div v-highlight="keyword">{{ originalText }}</div>
</template>
<script>
export default {
data() {
return {
originalText: 'This is another example with highlighted words',
keyword: 'highlighted'
}
},
directives: {
highlight: {
inserted(el, binding) {
const regex = new RegExp(binding.value, 'gi')
el.innerHTML = el.textContent.replace(
regex,
match => `<span style="background-color: #ffeb3b">${match}</span>`
)
}
}
}
}
</script>
使用组件封装
创建一个可重用的高亮组件,方便在多个地方使用。

<template>
<highlight :text="text" :query="searchQuery"></highlight>
</template>
<script>
import Highlight from './Highlight.vue'
export default {
components: { Highlight },
data() {
return {
text: 'Component-based highlighting example',
searchQuery: 'highlighting'
}
}
}
</script>
Highlight.vue 组件实现:
<template>
<div v-html="processedText"></div>
</template>
<script>
export default {
props: ['text', 'query'],
computed: {
processedText() {
if (!this.query) return this.text
const regex = new RegExp(this.query, 'gi')
return this.text.replace(
regex,
match => `<span class="highlight">${match}</span>`
)
}
}
}
</script>
<style>
.highlight {
background-color: yellow;
font-weight: bold;
}
</style>
使用第三方库
可以考虑使用专门的高亮库如 mark.js 来实现更复杂的高亮功能。

安装 mark.js:
npm install mark.js
使用示例:
<template>
<div ref="content">
{{ content }}
</div>
</template>
<script>
import Mark from 'mark.js'
export default {
data() {
return {
content: 'Text content to be highlighted goes here',
searchTerm: 'highlighted'
}
},
mounted() {
this.highlightText()
},
methods: {
highlightText() {
const instance = new Mark(this.$refs.content)
instance.mark(this.searchTerm, {
className: 'custom-highlight'
})
}
}
}
</script>
<style>
.custom-highlight {
background-color: #ffeb3b;
padding: 0 2px;
}
</style>
注意事项
- 使用
v-html时要注意 XSS 攻击风险,确保内容可信 - 高亮逻辑区分大小写时需调整正则表达式标志
- 对于大量文本的高亮操作,考虑性能优化
- 可以扩展高亮样式,添加动画或其他视觉效果
以上方法可以根据具体需求选择或组合使用,实现灵活多样的文本高亮效果。






