)。…">
当前位置:首页 > VUE

vue实现搜索高亮显示

2026-01-22 13:32:19VUE

实现搜索高亮的基本思路

在Vue中实现搜索高亮的核心逻辑是通过正则表达式匹配关键词,并将匹配到的内容替换为带有高亮样式的HTML标签(如<span class="highlight">)。需要结合Vue的数据绑定和动态渲染特性。

定义高亮样式

在CSS中定义高亮样式,例如:

.highlight {
  background-color: yellow;
  color: black;
  font-weight: bold;
}

创建高亮方法

在Vue组件中定义一个方法,用于处理文本并返回高亮后的HTML字符串:

vue实现搜索高亮显示

methods: {
  highlightText(text, keyword) {
    if (!keyword) return text;
    const regex = new RegExp(keyword, 'gi');
    return text.replace(regex, match => `<span class="highlight">${match}</span>`);
  }
}

模板中使用高亮

在模板中通过v-html指令渲染高亮后的内容(注意防范XSS风险):

<template>
  <div>
    <input v-model="searchKeyword" placeholder="输入搜索关键词" />
    <div v-html="highlightText(originalText, searchKeyword)"></div>
  </div>
</template>

处理多关键词高亮

若需支持多关键词高亮,可扩展高亮方法:

vue实现搜索高亮显示

highlightText(text, keywords) {
  if (!keywords) return text;
  const keywordArray = keywords.split(' ');
  let result = text;
  keywordArray.forEach(keyword => {
    if (keyword) {
      const regex = new RegExp(keyword, 'gi');
      result = result.replace(regex, match => `<span class="highlight">${match}</span>`);
    }
  });
  return result;
}

安全性注意事项

使用v-html时需确保内容可信,避免XSS攻击。可通过DOMPurify等库过滤危险内容:

import DOMPurify from 'dompurify';
// ...
highlightText(text, keyword) {
  const highlighted = /* 高亮逻辑 */;
  return DOMPurify.sanitize(highlighted);
}

性能优化建议

对于大量文本的高亮操作,可通过以下方式优化:

  • 使用防抖(debounce)延迟高亮计算
  • 避免在每次输入时重新处理整个文本
  • 考虑虚拟滚动技术处理长列表

完整组件示例

<template>
  <div>
    <input v-model="searchKeyword" placeholder="输入搜索关键词" />
    <div v-html="safeHighlightedText"></div>
  </div>
</template>

<script>
import DOMPurify from 'dompurify';

export default {
  data() {
    return {
      originalText: '这是一段需要高亮显示的示例文本,包含多个关键词。',
      searchKeyword: ''
    };
  },
  computed: {
    safeHighlightedText() {
      return DOMPurify.sanitize(this.highlightText(this.originalText, this.searchKeyword));
    }
  },
  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;
}
</style>

标签: vue高亮
分享给朋友:

相关文章

vue实现下拉刷新组件

vue实现下拉刷新组件

实现下拉刷新组件的核心思路 下拉刷新功能通常通过监听触摸事件、滚动位置和动画效果实现。Vue中可以利用自定义指令或封装组件完成,以下为两种常见实现方式。 基于自定义指令的实现 创建指令监听触摸事件,…

vue实现https

vue实现https

Vue 中实现 HTTPS 的步骤 在 Vue 项目中实现 HTTPS 主要涉及开发环境配置和生产环境部署。以下是具体方法: 开发环境配置(Vue CLI 或 Vite) 使用 mkcert 生成…

vue实现Siri

vue实现Siri

Vue 实现 Siri 风格语音交互 实现类似 Siri 的语音交互功能需要结合语音识别、语音合成和前端交互逻辑。Vue 作为前端框架,可以很好地管理这些功能的交互状态。 语音识别集成 使用 Web…

vue实现tap

vue实现tap

Vue 实现 Tap 事件 在移动端开发中,Tap 事件比 Click 事件更常用,因为 Click 事件有 300ms 延迟。以下是几种在 Vue 中实现 Tap 事件的方法。 使用第三方库 安装…

vue搜索实现

vue搜索实现

Vue 搜索功能实现方法 基于计算属性的搜索 在 Vue 中可以通过计算属性实现简单的搜索功能。这种方式适合小型数据集,利用 JavaScript 的 filter 方法进行筛选。 data() {…

vue实现curd

vue实现curd

Vue实现CRUD操作 初始化Vue项目 使用Vue CLI创建新项目,安装必要依赖如axios用于HTTP请求 vue create crud-demo cd crud-demo npm inst…