如何用vue实现高亮
使用 Vue 实现高亮功能
高亮功能通常用于搜索关键词、标记重要内容或交互式文本选择。以下是几种实现方式:
基础文本高亮
通过绑定动态样式或类名实现简单高亮效果:

<template>
<div>
<p :class="{ 'highlight': isHighlighted }">可高亮文本</p>
<button @click="isHighlighted = !isHighlighted">切换高亮</button>
</div>
</template>
<script>
export default {
data() {
return {
isHighlighted: false
}
}
}
</script>
<style>
.highlight {
background-color: yellow;
font-weight: bold;
}
</style>
关键词搜索高亮
实现搜索关键词在文本中的高亮显示:

<template>
<div>
<input v-model="searchText" placeholder="输入关键词"/>
<div v-html="highlightedContent"></div>
</div>
</template>
<script>
export default {
data() {
return {
originalText: '这是一段包含重要信息的示例文本,信息可能重复出现。',
searchText: ''
}
},
computed: {
highlightedContent() {
if (!this.searchText) return this.originalText
const regex = new RegExp(this.searchText, 'gi')
return this.originalText.replace(regex,
match => `<span class="highlight">${match}</span>`
)
}
}
}
</script>
多色高亮标记
实现不同颜色的高亮标注系统:
<template>
<div>
<p ref="textEl">选择文本后点击颜色按钮进行高亮标记</p>
<button
v-for="color in colors"
:key="color"
:style="{backgroundColor: color}"
@click="highlightSelection(color)"
></button>
</div>
</template>
<script>
export default {
data() {
return {
colors: ['yellow', 'lime', 'cyan', 'pink']
}
},
methods: {
highlightSelection(color) {
const selection = window.getSelection()
if (selection.toString()) {
const span = document.createElement('span')
span.style.backgroundColor = color
span.appendChild(selection.getRangeAt(0).cloneContents())
const range = selection.getRangeAt(0)
range.deleteContents()
range.insertNode(span)
}
}
}
}
</script>
注意事项
- 使用
v-html时需注意XSS风险,确保内容可信或进行转义处理 - 动态高亮可能影响性能,长文本建议使用虚拟滚动优化
- 高亮样式应考虑无障碍访问,确保颜色对比度符合WCAG标准
进阶实现
对于复杂场景可考虑:
- 使用自定义指令封装高亮逻辑
- 结合Vuex管理高亮状态
- 实现持久化存储高亮标记
- 使用第三方库如mark.js集成更多功能






