当前位置:首页 > VUE

vue实现搜索高亮

2026-02-17 18:34:15VUE

实现搜索高亮的方法

在Vue中实现搜索高亮可以通过多种方式完成,以下是几种常见的实现方法:

使用v-html和正则表达式

通过正则表达式匹配搜索关键词,并用HTML标签包裹匹配到的内容,最后使用v-html渲染结果。

<template>
  <div>
    <input v-model="searchText" placeholder="输入搜索内容" />
    <div v-html="highlightedText"></div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      originalText: '这是一段需要高亮显示的文本内容',
      searchText: ''
    }
  },
  computed: {
    highlightedText() {
      if (!this.searchText) return this.originalText
      const regex = new RegExp(this.searchText, 'gi')
      return this.originalText.replace(regex, match => 
        `<span style="background-color: yellow">${match}</span>`
      )
    }
  }
}
</script>

使用自定义指令

创建自定义指令来处理文本高亮,使代码更模块化和可复用。

Vue.directive('highlight', {
  inserted(el, binding) {
    const text = el.textContent
    const searchText = binding.value
    if (!searchText) return

    const regex = new RegExp(searchText, 'gi')
    el.innerHTML = text.replace(regex, match => 
      `<span style="background-color: yellow">${match}</span>`
    )
  },
  update(el, binding) {
    const text = el.textContent
    const searchText = binding.value
    const regex = new RegExp(searchText, 'gi')
    el.innerHTML = text.replace(regex, match => 
      `<span style="background-color: yellow">${match}</span>`
    )
  }
})

使用组件封装

创建一个专门的高亮组件,接收原始文本和搜索词作为props。

<template>
  <span>
    <template v-for="(part, index) in parts">
      <span 
        v-if="part.highlight" 
        :key="index" 
        style="background-color: yellow"
      >
        {{ part.text }}
      </span>
      <span v-else :key="index">
        {{ part.text }}
      </span>
    </template>
  </span>
</template>

<script>
export default {
  props: {
    text: String,
    search: String
  },
  computed: {
    parts() {
      if (!this.search) return [{ text: this.text, highlight: false }]

      const regex = new RegExp(this.search, 'gi')
      const matches = [...this.text.matchAll(regex)]

      if (matches.length === 0) return [{ text: this.text, highlight: false }]

      let lastIndex = 0
      const parts = []

      matches.forEach(match => {
        const index = match.index
        if (index > lastIndex) {
          parts.push({
            text: this.text.substring(lastIndex, index),
            highlight: false
          })
        }

        parts.push({
          text: match[0],
          highlight: true
        })

        lastIndex = index + match[0].length
      })

      if (lastIndex < this.text.length) {
        parts.push({
          text: this.text.substring(lastIndex),
          highlight: false
        })
      }

      return parts
    }
  }
}
</script>

注意事项

使用v-html时需要注意XSS攻击风险,确保搜索内容来自可信来源或进行适当转义。

高亮实现应考虑性能问题,特别是处理大量文本时,可以使用防抖技术优化搜索输入处理。

对于复杂搜索需求,可能需要更高级的正则表达式或分词处理来改善匹配效果。

vue实现搜索高亮

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

相关文章

vue实现双折线图

vue实现双折线图

实现双折线图的步骤 安装必要的依赖库(如 ECharts 或 Chart.js),这里以 ECharts 为例: npm install echarts --save 在 Vue 组件中引入 ECh…

vue实现语音

vue实现语音

Vue 实现语音功能的方法 使用 Web Speech API Vue 可以结合 Web Speech API 实现语音识别和合成功能。Web Speech API 包含 SpeechRecognit…

vue实现滑块

vue实现滑块

Vue 实现滑块组件的方法 使用原生 HTML 和 Vue 指令 通过 Vue 的 v-model 和事件监听实现基础滑块功能。创建一个包含 input 元素的组件,类型设置为 range,并绑定到…

vue筛选实现

vue筛选实现

Vue 筛选实现方法 使用计算属性实现筛选 计算属性是 Vue 中实现数据筛选的常用方式。通过定义一个计算属性,可以根据输入的条件动态过滤数据。 <template> <di…

vue实现表白

vue实现表白

Vue 实现表白页面 使用 Vue 可以快速创建一个动态、交互式的表白页面。以下是一个简单的实现方案: 基础结构 创建一个 Vue 项目或单文件组件,包含以下核心部分: <templat…

vue插件实现

vue插件实现

Vue 插件实现方法 Vue 插件是一种向 Vue 应用程序添加全局功能的机制。插件可以包含全局指令、过滤器、混入、实例方法等。 插件的基本结构 一个 Vue 插件通常是一个对象或函数,需要暴露一…