vue实现高亮显示
Vue 实现高亮显示的方法
在 Vue 中实现高亮显示通常涉及文本匹配和样式动态切换。以下是几种常见实现方式:
使用 v-html 和字符串替换
通过替换目标文本为带样式的 HTML 实现高亮:
<template>
<div v-html="highlightedText"></div>
</template>
<script>
export default {
data() {
return {
originalText: 'This is a sample text for highlighting',
searchTerm: 'sample'
}
},
computed: {
highlightedText() {
return this.originalText.replace(
new RegExp(this.searchTerm, 'gi'),
match => `<span class="highlight">${match}</span>`
)
}
}
}
</script>
<style>
.highlight {
background-color: yellow;
font-weight: bold;
}
</style>
使用自定义指令
创建可复用的高亮指令:
Vue.directive('highlight', {
inserted(el, binding) {
const text = el.textContent
const term = binding.value
const regex = new RegExp(term, 'gi')
el.innerHTML = text.replace(regex, match =>
`<span style="background-color: yellow">${match}</span>`
)
}
})
// 使用方式
<div v-highlight="'search term'">Some text containing search term</div>
基于组件的高亮方案
创建可复用的高亮组件:
<template>
<span>
<span v-for="(part, index) in parts" :key="index" :class="{ highlight: part.highlight }">
{{ part.text }}
</span>
</span>
</template>
<script>
export default {
props: ['text', 'query'],
computed: {
parts() {
const regex = new RegExp(`(${this.query})`, 'gi')
return this.text.split(regex).map(part => ({
text: part,
highlight: regex.test(part)
}))
}
}
}
</script>
使用第三方库
考虑使用专门的高亮库如 mark.js:
npm install mark.js
// 组件中使用
import Mark from 'mark.js'
export default {
methods: {
highlight() {
const instance = new Mark(this.$refs.highlightContainer)
instance.mark(this.searchTerm, {
className: 'highlight'
})
}
},
mounted() {
this.highlight()
}
}
动态样式绑定
对于简单场景可使用动态 class 绑定:
<template>
<span :class="{ 'text-yellow': shouldHighlight }">
{{ text }}
</span>
</template>
<script>
export default {
props: ['text', 'shouldHighlight']
}
</script>
每种方法适用于不同场景,v-html 方案适合简单替换,自定义指令提供更好的复用性,组件方案更灵活,第三方库适合复杂高亮需求。注意使用 v-html 时需防范 XSS 风险,对用户输入内容进行适当过滤。







