vue实现高亮
Vue 实现高亮的方法
在 Vue 中实现高亮功能可以通过多种方式实现,以下是一些常见的方法:
使用 v-html 指令
通过 v-html 指令可以动态渲染包含 HTML 标签的字符串,从而实现高亮效果。需要确保内容的安全性,避免 XSS 攻击。

<template>
<div v-html="highlightedText"></div>
</template>
<script>
export default {
data() {
return {
text: 'This is a sample text to highlight',
searchTerm: 'sample'
};
},
computed: {
highlightedText() {
const regex = new RegExp(this.searchTerm, 'gi');
return this.text.replace(regex, match => `<span class="highlight">${match}</span>`);
}
}
};
</script>
<style>
.highlight {
background-color: yellow;
font-weight: bold;
}
</style>
使用自定义指令
可以创建一个自定义指令来动态高亮匹配的文本。

<template>
<div v-highlight="searchTerm">{{ text }}</div>
</template>
<script>
export default {
data() {
return {
text: 'This is a sample text to highlight',
searchTerm: 'sample'
};
},
directives: {
highlight: {
inserted(el, binding) {
const regex = new RegExp(binding.value, 'gi');
el.innerHTML = el.textContent.replace(regex, match => `<span class="highlight">${match}</span>`);
},
update(el, binding) {
const regex = new RegExp(binding.value, 'gi');
el.innerHTML = el.textContent.replace(regex, match => `<span class="highlight">${match}</span>`);
}
}
}
};
</script>
<style>
.highlight {
background-color: yellow;
font-weight: bold;
}
</style>
使用第三方库
可以使用第三方库如 mark.js 来实现更复杂的高亮功能。
<template>
<div ref="content">{{ text }}</div>
</template>
<script>
import Mark from 'mark.js';
export default {
data() {
return {
text: 'This is a sample text to highlight',
searchTerm: 'sample'
};
},
mounted() {
this.highlightText();
},
watch: {
searchTerm() {
this.highlightText();
}
},
methods: {
highlightText() {
const markInstance = new Mark(this.$refs.content);
markInstance.unmark();
markInstance.mark(this.searchTerm, {
className: 'highlight'
});
}
}
};
</script>
<style>
.highlight {
background-color: yellow;
font-weight: bold;
}
</style>
动态样式绑定
通过动态绑定样式类来实现高亮效果。
<template>
<div>
<span
v-for="(word, index) in words"
:key="index"
:class="{ highlight: word === searchTerm }"
>
{{ word }}
</span>
</div>
</template>
<script>
export default {
data() {
return {
text: 'This is a sample text to highlight',
searchTerm: 'sample'
};
},
computed: {
words() {
return this.text.split(' ');
}
}
};
</script>
<style>
.highlight {
background-color: yellow;
font-weight: bold;
}
</style>
注意事项
- 使用
v-html时需注意安全性,避免注入恶意代码。 - 自定义指令适用于需要复用高亮逻辑的场景。
- 第三方库如
mark.js提供了更多高亮选项和灵活性。 - 动态样式绑定适用于简单的文本高亮需求。






