vue实现搜索高亮
实现搜索高亮的方法
使用 v-html 和正则表达式
通过正则表达式匹配关键词并替换为高亮标签,结合 v-html 渲染结果。
<template>
<div>
<input v-model="searchText" placeholder="输入搜索内容" />
<div v-html="highlightedContent"></div>
</div>
</template>
<script>
export default {
data() {
return {
content: '这里是需要被搜索的文本内容',
searchText: ''
};
},
computed: {
highlightedContent() {
if (!this.searchText) return this.content;
const regex = new RegExp(this.searchText, 'gi');
return this.content.replace(regex, match =>
`<span style="background-color: yellow">${match}</span>`
);
}
}
};
</script>
使用自定义指令
封装高亮逻辑为自定义指令,增强复用性。
<template>
<div>
<input v-model="searchText" />
<div v-highlight="searchText">{{ content }}</div>
</div>
</template>
<script>
export default {
directives: {
highlight: {
updated(el, binding) {
const text = el.textContent;
if (!binding.value) {
el.innerHTML = text;
return;
}
const regex = new RegExp(binding.value, 'gi');
el.innerHTML = text.replace(regex, match =>
`<span style="background-color: yellow">${match}</span>`
);
}
}
},
data() {
return {
content: '示例文本内容',
searchText: ''
};
}
};
</script>
使用第三方库
借助 mark.js 实现更复杂的高亮效果。
<template>
<div>
<input v-model="searchText" />
<div ref="content">需要高亮的文本内容</div>
</div>
</template>
<script>
import Mark from 'mark.js';
export default {
data() {
return {
searchText: ''
};
},
watch: {
searchText(newVal) {
const markInstance = new Mark(this.$refs.content);
markInstance.unmark();
if (newVal) markInstance.mark(newVal);
}
}
};
</script>
动态样式类名
通过动态绑定类名实现高亮样式切换。
<template>
<div>
<input v-model="searchText" />
<div :class="{ 'highlight': searchText }">{{ content }}</div>
</div>
</template>
<script>
export default {
data() {
return {
content: '动态样式类名示例',
searchText: ''
};
}
};
</script>
<style>
.highlight {
background-color: yellow;
}
</style>
高亮组件封装
将高亮逻辑抽象为独立组件,提高可维护性。
<template>
<div>
<input v-model="searchText" />
<Highlight :text="content" :query="searchText" />
</div>
</template>
<script>
import Highlight from './Highlight.vue';
export default {
components: { Highlight },
data() {
return {
content: '组件封装示例',
searchText: ''
};
}
};
</script>
在 Highlight.vue 中实现核心逻辑:

<template>
<div v-html="highlightedText"></div>
</template>
<script>
export default {
props: ['text', 'query'],
computed: {
highlightedText() {
if (!this.query) return this.text;
const regex = new RegExp(this.query, 'gi');
return this.text.replace(regex, match =>
`<span class="highlight">${match}</span>`
);
}
}
};
</script>
<style>
.highlight {
background-color: yellow;
}
</style>
注意事项
- 使用
v-html时需防范 XSS 攻击,确保内容可信。 - 正则表达式需处理特殊字符,避免匹配错误。
- 高亮样式可根据需求自定义颜色或动画效果。






