当前位置:首页 > 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实现通知

Vue 实现通知功能的方法 使用 Vue 实现通知功能可以通过多种方式实现,以下是一些常见的方法: 使用 Vue 的全局事件总线 在 Vue 中可以通过事件总线实现通知功能。创建一个全局事件总线,然…

vue实现setinterval

vue实现setinterval

在 Vue 中使用 setInterval Vue 中可以通过生命周期钩子和方法结合 setInterval 实现定时任务。以下是一个完整的实现示例: <template> <…

vue实现swipe

vue实现swipe

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

vue实现框选

vue实现框选

Vue 实现框选功能 在 Vue 中实现框选功能通常需要监听鼠标事件,计算选区范围,并根据选区范围高亮或选中元素。以下是实现框选功能的关键步骤。 监听鼠标事件 在 Vue 模板中,为容器元素绑定鼠标…

vue列表查询实现

vue列表查询实现

实现 Vue 列表查询功能 基础列表渲染 在 Vue 中可以通过 v-for 指令实现列表渲染,结合计算属性动态过滤数据: <template> <div> &l…

vue实现左右菜单联动实现

vue实现左右菜单联动实现

Vue 实现左右菜单联动 使用事件总线通信 在 Vue 中可以通过事件总线实现左右菜单的通信。创建一个中央事件总线实例,让左右菜单通过事件监听和触发实现联动。 // eventBus.js impo…