)。…">
当前位置:首页 > 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中实现注册功能通常需要结合前端表单和后端API交互。以下是完整的实现方案: 创建注册表单组件 注册表单需要包含用户名、邮箱、密码等基本字段,并进行表单验证: <…

vue实现打印二维码

vue实现打印二维码

安装二维码生成库 使用 qrcode 或 vue-qrcode 库生成二维码。通过 npm 安装: npm install qrcode vue-qrcode 生成二维码 在 Vue 组…

实现vue

实现vue

安装Vue.js 通过npm安装Vue.js是最常见的方式。确保已安装Node.js和npm,运行以下命令: npm install vue 或者使用CDN直接引入: <script s…

vue实现钟表

vue实现钟表

使用 Vue 实现动态钟表 以下是一个基于 Vue 3 的动态钟表实现方案,包含时分秒指针和数字时间显示。 模板部分 <template> <div class="clock…

vue优秀实现

vue优秀实现

Vue.js 优秀实现方法 响应式数据管理 使用 Vue 的 ref 和 reactive 处理基础类型和对象类型数据,结合 computed 计算属性优化渲染性能。对于复杂状态,推荐 Pinia 替…

vue 指令实现

vue 指令实现

Vue 指令实现 Vue 指令是 Vue.js 提供的特殊属性,用于在 DOM 元素上添加特殊行为。指令以 v- 前缀开头,例如 v-model、v-if、v-for 等。以下是实现自定义指令和常用内…