vue如何实现文字高亮
实现文字高亮的方法
在Vue中实现文字高亮通常可以通过以下几种方式完成,具体取决于需求场景:
使用v-html指令
通过动态绑定HTML内容,将需要高亮的文字包裹在<span>标签中并添加样式类:
<template>
<div v-html="highlightText(text, keyword)"></div>
</template>
<script>
export default {
methods: {
highlightText(text, keyword) {
if (!keyword) return text;
const regex = new RegExp(keyword, 'gi');
return text.replace(regex, match => `<span class="highlight">${match}</span>`);
}
}
}
</script>
<style>
.highlight {
background-color: yellow;
color: black;
}
</style>
使用计算属性

通过计算属性返回处理后的高亮文本,结合模板中的双花括号插值:
<template>
<div>{{ highlightedText }}</div>
</template>
<script>
export default {
computed: {
highlightedText() {
const keyword = 'Vue';
return this.text.replace(
new RegExp(keyword, 'gi'),
'<mark>$&</mark>'
);
}
}
}
</script>
使用第三方库

对于更复杂的高亮需求,可以使用专门的高亮库如mark.js:
<template>
<div ref="content">{{ text }}</div>
</template>
<script>
import Mark from 'mark.js';
export default {
mounted() {
const markInstance = new Mark(this.$refs.content);
markInstance.mark('keyword');
}
}
</script>
动态样式绑定
对于简单的单字高亮,可以使用动态class绑定:
<template>
<div>
<span
v-for="(char, index) in text"
:key="index"
:class="{ 'highlight': char === keyword }"
>
{{ char }}
</span>
</div>
</template>
每种方法适用于不同场景,v-html适合简单全局替换,计算属性适合响应式更新,第三方库适合复杂匹配,动态绑定适合精确控制单个字符样式。需要注意使用v-html时需防范XSS攻击,对用户输入内容进行转义处理。






