Vue 3 实现文章关键词高亮显示

发表于 2025-09-19 17:39:54 分类于 默认分类 阅读量 69

Vue 3 实现文章关键词高亮显示

在前端开发中,经常需要在文章列表或搜索结果中对关键词进行高亮显示。本文将介绍如何在 Vue 3 中实现对文章标题和描述的关键词高亮功能。


1. 场景示例

假设我们有如下文章数据:

const article = {
  id: 1,
  title: 'Vue 3 高亮显示关键词示例',
  description: '这是一个演示如何在 Vue 3 中对关键词高亮显示的文章描述'
}

我们希望在标题和描述中,如果包含关键字 Vue 3,就将其高亮显示。


2. 模板实现

在 Vue 3 组件模板中使用 v-html 渲染高亮文本:

<template>
  <a 
    :href="'/article/detail?articleId=' + article.id" 
    @click.prevent="goArticleDetail(article.id)" 
    class="cursor-pointer"
  >
    <h2 
      class="mb-2 text-2xl font-bold tracking-tight text-gray-900 dark:text-white"
      v-html="highlight(article.title, keyword)"
    ></h2>
  </a>
  <p 
    class="mb-3 font-normal text-gray-500 dark:text-gray-400" 
    style="overflow: hidden; text-overflow: ellipsis;"
    v-html="highlight(article.description, keyword)"
  ></p>
</template>

3. 组件逻辑

<script setup>
import { ref } from 'vue'

// 文章数据
const article = ref({
  id: 1,
  title: 'Vue 3 高亮显示关键词示例',
  description: '这是一个演示如何在 Vue 3 中对关键词高亮显示的文章描述'
})

// 要高亮的关键词
const keyword = ref('Vue 3')

function escapeHtml(text: string) {
  return text
      .replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;')
      .replace(/'/g, '&#039;')
}

/**
 * 高亮方法
 * @param text
 */
function highlight(text: string) {
  const _keyword = keyword.value.trim()
  if (!_keyword) return escapeHtml(text)

  const escaped = _keyword.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&')
  const regex = new RegExp(`(${escaped})`, 'gi')

  return escapeHtml(text).replace(regex, '<span class="bg-yellow-200">$1</span>')
}

// 点击文章跳转
function goArticleDetail(id) {
  console.log('跳转文章详情', id)
}
</script>

4. 样式说明

在示例中,使用了 Tailwind CSS 的 bg-yellow-200 给关键词添加黄色背景高亮。你也可以使用自定义样式:

.highlight {
  background-color: yellow;
}

并在 highlight 方法中改为:

return text.replace(regex, '<span class="highlight">$1</span>')

5. 功能总结

  • 支持标题和描述的关键词高亮显示
  • 使用 v-html 渲染带 HTML 的字符串
  • 支持忽略大小写
  • 可通过 Tailwind 或自定义 CSS 设置高亮样式

6. 扩展

如果你希望支持 多个关键词同时高亮,可以将 keyword 改为数组,然后循环生成正则表达式即可。


这样,你就可以在 Vue 3 中轻松实现文章列表的关键词高亮功能,提高搜索和展示效果。