当前位置:首页 > VUE

vue实现搜索文字变色

2026-02-24 23:01:29VUE

实现搜索文字变色的方法

在Vue中实现搜索文字变色功能,可以通过以下步骤完成:

方法一:使用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; color: black">${match}</span>`
      )
    }
  }
}
</script>

方法二:使用自定义指令

<template>
  <div>
    <input v-model="searchText" placeholder="输入搜索内容" />
    <div v-highlight="searchText">{{ originalText }}</div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      originalText: '这是一段需要搜索的文本内容,可以包含多个关键词',
      searchText: ''
    }
  },
  directives: {
    highlight: {
      inserted(el, binding) {
        el.innerHTML = el.textContent.replace(
          new RegExp(binding.value, 'gi'),
          match => `<span style="background-color: yellow">${match}</span>`
        )
      },
      update(el, binding) {
        el.innerHTML = el.textContent.replace(
          new RegExp(binding.value, 'gi'),
          match => `<span style="background-color: yellow">${match}</span>`
        )
      }
    }
  }
}
</script>

方法三:使用组件封装

创建一个可重用的HighlightText组件:

<template>
  <span v-html="processedText"></span>
</template>

<script>
export default {
  props: {
    text: String,
    query: String
  },
  computed: {
    processedText() {
      if (!this.query) return this.text
      const regex = new RegExp(this.query, 'gi')
      return this.text.replace(regex, match => 
        `<span style="background-color: yellow">${match}</span>`
      )
    }
  }
}
</script>

使用方法:

vue实现搜索文字变色

<template>
  <div>
    <input v-model="searchText" />
    <HighlightText :text="originalText" :query="searchText" />
  </div>
</template>

注意事项

  • 使用v-html时要注意XSS攻击风险,确保内容来源可信
  • 对于大量文本的搜索高亮,考虑使用虚拟滚动优化性能
  • 可以扩展高亮样式,支持多种颜色和样式配置
  • 考虑添加区分大小写的选项,增强搜索灵活性

标签: 文字vue
分享给朋友:

相关文章

vue实现visual

vue实现visual

Vue 实现可视化(Visual)的常见方法 在 Vue 中实现可视化通常涉及数据可视化库的集成,以下是几种主流方案: 使用 ECharts ECharts 是一个强大的 JavaScript 图表…

vue实现点击

vue实现点击

实现点击事件的基本方法 在Vue中实现点击事件可以通过v-on指令或@简写方式绑定。以下是常见的点击事件绑定方法: <template> <button v-on:click=…

vue 实现菜单

vue 实现菜单

Vue 实现菜单的方法 使用 Vue 实现菜单可以通过多种方式,以下是几种常见的方法: 使用 Vue Router 实现动态路由菜单 通过 Vue Router 可以动态生成菜单,根据路由配置自动渲…

vue实现抖动

vue实现抖动

Vue 实现抖动效果 在 Vue 中实现抖动效果可以通过 CSS 动画或 JavaScript 动画库来实现。以下是几种常见的方法: 使用 CSS 动画 通过定义 @keyframes 动画并在 V…

vue实现刷卡

vue实现刷卡

Vue 实现刷卡效果 在 Vue 中实现刷卡效果可以通过 CSS 动画和 Vue 的过渡系统结合完成。以下是一种常见的实现方式: 基础实现方法 安装 Vue 过渡依赖(如果尚未安装): npm i…

vue nexttrick实现

vue nexttrick实现

Vue 中 nextTick 的实现原理 nextTick 是 Vue 提供的一个异步方法,用于在下次 DOM 更新循环结束之后执行延迟回调。它利用了 JavaScript 的事件循环机制,确保回调在…