vue实现文本标记
Vue 实现文本标记的方法
使用 v-html 指令
在 Vue 中可以通过 v-html 指令动态渲染 HTML 内容。例如,将需要标记的文本包裹在 <mark> 标签中:
<template>
<div v-html="markedText"></div>
</template>
<script>
export default {
data() {
return {
originalText: 'This is a sample text to be marked',
searchTerm: 'sample'
}
},
computed: {
markedText() {
const regex = new RegExp(this.searchTerm, 'gi')
return this.originalText.replace(regex, match => `<mark>${match}</mark>`)
}
}
}
</script>
使用自定义组件
创建一个专门的文本标记组件,提供更灵活的控制:
<template>
<div>
<marked-text
:text="originalText"
:search="searchTerm"
highlight-class="custom-highlight"
/>
</div>
</template>
<script>
import MarkedText from './MarkedText.vue'
export default {
components: { MarkedText },
data() {
return {
originalText: 'Another example for text marking',
searchTerm: 'example'
}
}
}
</script>
在 MarkedText.vue 组件中:

<template>
<span v-html="processedText"></span>
</template>
<script>
export default {
props: {
text: String,
search: String,
highlightClass: {
type: String,
default: 'mark'
}
},
computed: {
processedText() {
if (!this.search) return this.text
const regex = new RegExp(this.escapeRegExp(this.search), 'gi')
return this.text.replace(regex, match =>
`<span class="${this.highlightClass}">${match}</span>`
)
}
},
methods: {
escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
}
}
}
</script>
<style>
.mark {
background-color: yellow;
color: black;
}
.custom-highlight {
background-color: #ffeb3b;
font-weight: bold;
}
</style>
使用第三方库
对于更复杂的文本标记需求,可以考虑使用专门的高亮库如 mark.js:
-
安装 mark.js:

npm install mark.js -
在 Vue 组件中使用:
<template> <div ref="markContainer"> {{ originalText }} </div> </template>
export default { data() { return { originalText: 'Text to be marked using mark.js library', searchTerm: 'marked' } }, mounted() { this.highlightText() }, watch: { searchTerm() { this.highlightText() } }, methods: { highlightText() { const markInstance = new Mark(this.$refs.markContainer) markInstance.unmark() markInstance.mark(this.searchTerm, { className: 'highlight', acrossElements: true }) } } }
.highlight { background-color: #ffcc80; padding: 0 2px; } ```动态样式绑定
通过动态 class 绑定实现更灵活的标记样式:
<template>
<div>
<span
v-for="(word, index) in words"
:key="index"
:class="{ 'is-marked': isMarked(word) }"
>
{{ word }}
</span>
</div>
</template>
<script>
export default {
data() {
return {
originalText: 'Dynamic text highlighting example',
searchTerm: 'highlighting'
}
},
computed: {
words() {
return this.originalText.split(' ')
}
},
methods: {
isMarked(word) {
return word.toLowerCase().includes(this.searchTerm.toLowerCase())
}
}
}
</script>
<style>
.is-marked {
background: linear-gradient(to top, #fffcdc 40%, transparent 40%);
font-style: italic;
}
</style>
这些方法提供了从简单到复杂的文本标记实现方案,可以根据具体需求选择最适合的方式。





