vue实现检索内容标记
Vue 实现检索内容标记的方法
使用 v-html 和正则表达式替换
在 Vue 中可以通过 v-html 指令结合正则表达式来实现检索内容的高亮标记。创建一个方法处理文本,将匹配关键词的部分用 <span> 标签包裹并添加高亮样式。
<template>
<div v-html="highlightText(content, 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;
font-weight: bold;
}
</style>
使用自定义指令
对于更复杂的场景,可以创建自定义指令来实现高亮功能。这种方式更加灵活,可以复用。
Vue.directive('highlight', {
inserted(el, binding) {
const text = el.textContent;
const keyword = binding.value;
if (!keyword) return;
const regex = new RegExp(keyword, 'gi');
el.innerHTML = text.replace(regex, match =>
`<span style="background-color: yellow;">${match}</span>`
);
},
update(el, binding) {
const text = el.textContent;
const keyword = binding.value;
if (!keyword) return;
const regex = new RegExp(keyword, 'gi');
el.innerHTML = text.replace(regex, match =>
`<span style="background-color: yellow;">${match}</span>`
);
}
});
使用计算属性动态高亮
结合计算属性可以实现动态高亮效果,特别适用于列表渲染的场景。
<template>
<div>
<div v-for="item in items" :key="item.id">
<span v-html="highlight(item.text)"></span>
</div>
</div>
</template>
<script>
export default {
computed: {
highlight() {
return (text) => {
if (!this.keyword) return text;
const regex = new RegExp(this.keyword, 'gi');
return text.replace(regex, match =>
`<span class="highlight">${match}</span>`
);
};
}
}
}
</script>
使用第三方库
如果需要更强大的搜索和高亮功能,可以使用第三方库如 mark.js。
import Mark from 'mark.js';
export default {
mounted() {
const instance = new Mark(this.$el);
instance.mark(this.keyword);
},
watch: {
keyword(newVal) {
const instance = new Mark(this.$el);
instance.unmark().mark(newVal);
}
}
};
处理特殊字符
在实现高亮时,需要注意转义正则表达式的特殊字符,避免匹配错误。

methods: {
escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
},
highlightText(text, keyword) {
if (!keyword) return text;
const escapedKeyword = this.escapeRegExp(keyword);
const regex = new RegExp(escapedKeyword, 'gi');
return text.replace(regex, match => `<span class="highlight">${match}</span>`);
}
}
通过以上方法,可以在 Vue 中灵活实现检索内容的标记功能,根据需求选择最适合的方案。






