)包裹,最后通过v-htm…">
当前位置:首页 > VUE

vue实现搜索高亮显示

2026-02-23 04:30:23VUE

实现搜索高亮的基本思路

在Vue中实现搜索高亮的核心是通过正则表达式匹配关键词,并将匹配到的内容用HTML标签(如<span class="highlight">)包裹,最后通过v-html渲染处理后的文本。需注意安全性问题,避免XSS攻击。

方法一:使用计算属性处理高亮

定义一个计算属性,将原始文本中的关键词替换为高亮样式:

<template>
  <div>
    <input v-model="searchText" placeholder="输入搜索词" />
    <div v-html="highlightedContent"></div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      content: "这里是需要高亮显示的文本内容,包含Vue和JavaScript关键词。",
      searchText: ""
    };
  },
  computed: {
    highlightedContent() {
      if (!this.searchText) return this.content;
      const regex = new RegExp(this.searchText, "gi");
      return this.content.replace(
        regex,
        match => `<span class="highlight">${match}</span>`
      );
    }
  }
};
</script>

<style>
.highlight {
  background-color: yellow;
  font-weight: bold;
}
</style>

注意事项:

vue实现搜索高亮显示

  • 使用v-html时需确保内容来源可信,避免XSS攻击。
  • 正则表达式中的gi表示全局匹配且忽略大小写。

方法二:封装高亮为全局指令

将高亮逻辑封装为Vue自定义指令,方便复用:

// main.js 或单独指令文件
Vue.directive('highlight', {
  bind(el, binding) {
    const text = el.textContent;
    const search = binding.value;
    if (!search) return;
    const regex = new RegExp(search, 'gi');
    el.innerHTML = text.replace(
      regex,
      match => `<span class="highlight">${match}</span>`
    );
  },
  update(el, binding) {
    // 搜索词变化时重新渲染
    const text = el.textContent;
    const search = binding.value;
    if (!search) {
      el.innerHTML = text;
      return;
    }
    const regex = new RegExp(search, 'gi');
    el.innerHTML = text.replace(
      regex,
      match => `<span class="highlight">${match}</span>`
    );
  }
});

// 组件中使用
<template>
  <div v-highlight="searchText">{{ content }}</div>
</template>

方法三:处理多关键词高亮

若需支持多个关键词高亮,可通过拆分搜索词并循环处理:

vue实现搜索高亮显示

computed: {
  highlightedContent() {
    if (!this.searchText) return this.content;
    const keywords = this.searchText.split(' ').filter(k => k.trim());
    let result = this.content;
    keywords.forEach(keyword => {
      const regex = new RegExp(keyword, 'gi');
      result = result.replace(
        regex,
        match => `<span class="highlight">${match}</span>`
      );
    });
    return result;
  }
}

安全增强建议

若内容可能包含用户输入,建议使用DOMPurify库过滤HTML:

npm install dompurify
import DOMPurify from 'dompurify';
computed: {
  highlightedContent() {
    const rawHtml = this.replaceKeywords(); // 替换逻辑
    return DOMPurify.sanitize(rawHtml);
  }
}

性能优化

对于长文本或高频搜索,可通过防抖(debounce)减少计算次数:

import { debounce } from 'lodash';
methods: {
  updateHighlight: debounce(function() {
    this.highlightedContent = this.calculateHighlight();
  }, 300)
}

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

相关文章

vue菜单实现

vue菜单实现

Vue 菜单实现方法 使用 Element UI 的菜单组件 Element UI 提供了现成的菜单组件,适合快速实现导航菜单。安装 Element UI 后,可以直接使用 el-menu 相关组件。…

vue实现剪辑

vue实现剪辑

Vue 实现视频剪辑功能 在Vue中实现视频剪辑功能通常需要结合HTML5的<video>元素和第三方库(如FFmpeg.js或Video.js)。以下是几种常见的实现方法: 使用FF…

vue实现路由

vue实现路由

Vue 路由的实现方法 Vue 路由可以通过 Vue Router 库来实现,Vue Router 是 Vue.js 官方的路由管理器,用于构建单页面应用(SPA)。 安装 Vue Router 通…

vue实现定时

vue实现定时

Vue 实现定时功能的方法 使用 setInterval 和 clearInterval 在 Vue 中可以通过 setInterval 和 clearInterval 实现定时功能。在组件的 mou…

vue实现swipe

vue实现swipe

Vue实现Swipe功能的方法 使用第三方库(推荐) Vue生态中有多个成熟的轮播/滑动组件库,例如vue-awesome-swiper或swiper/vue。以下是基于swiper/vue的实现示例…

vue实现slidetoggle

vue实现slidetoggle

Vue 实现 SlideToggle 效果 SlideToggle 是一种常见的交互效果,元素以滑动方式展开或收起。以下是几种实现方法: 使用 CSS Transition 和 v-show…