vue实现高亮
Vue 实现文本高亮的方法
在 Vue 中实现文本高亮可以通过多种方式完成,以下是几种常见的方法:
方法一:使用 v-html 指令
通过 v-html 指令可以动态插入 HTML 内容,将需要高亮的部分用 span 标签包裹并添加样式。
<template>
<div v-html="highlightedText"></div>
</template>
<script>
export default {
data() {
return {
text: '这是一段需要高亮的文本',
keyword: '高亮'
}
},
computed: {
highlightedText() {
return this.text.replace(
new RegExp(this.keyword, 'g'),
'<span style="background-color: yellow;">$&</span>'
)
}
}
}
</script>
方法二:使用组件和插槽
创建一个专门的高亮组件,通过插槽和 props 实现更灵活的高亮功能。

<template>
<highlight :text="text" :keyword="keyword" />
</template>
<script>
import Highlight from './Highlight.vue'
export default {
components: { Highlight },
data() {
return {
text: '使用组件实现高亮效果',
keyword: '组件'
}
}
}
</script>
Highlight.vue 组件实现:
<template>
<div>
<slot>
<span v-for="(part, index) in parts" :key="index">
<span v-if="part.highlight" class="highlight">{{ part.text }}</span>
<span v-else>{{ part.text }}</span>
</span>
</slot>
</div>
</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')
return this.text.split(regex).map(part => ({
text: part,
highlight: regex.test(part)
}))
}
}
}
</script>
<style>
.highlight {
background-color: yellow;
font-weight: bold;
}
</style>
方法三:使用第三方库
可以使用专门的高亮库如 mark.js 或 vue-highlight-words 来实现更复杂的高亮需求。

安装 vue-highlight-words:
npm install vue-highlight-words
使用示例:
<template>
<highlight-words :text="text" :query="keyword" />
</template>
<script>
import HighlightWords from 'vue-highlight-words'
export default {
components: { HighlightWords },
data() {
return {
text: '使用第三方库实现高亮',
keyword: '第三方库'
}
}
}
</script>
方法四:自定义指令
创建一个自定义指令来实现文本高亮功能。
<template>
<div v-highlight="{ keyword, color: 'yellow' }">{{ text }}</div>
</template>
<script>
export default {
directives: {
highlight: {
inserted(el, binding) {
const { keyword, color } = binding.value
if (!keyword) return
const regex = new RegExp(keyword, 'gi')
el.innerHTML = el.textContent.replace(
regex,
`<span style="background-color: ${color};">$&</span>`
)
}
}
},
data() {
return {
text: '使用自定义指令实现高亮',
keyword: '指令'
}
}
}
</script>
注意事项
- 使用 v-html 时要注意 XSS 攻击风险,确保内容安全
- 高亮功能应考虑大小写敏感需求
- 对于大量文本的高亮操作,注意性能优化
- 高亮样式可以根据需求自定义,不仅仅是背景色
以上方法可以根据具体项目需求选择使用,组件化和自定义指令的方式更适合在大型项目中复用。






