当前位置:首页 > VUE

vue实现搜索变色

2026-03-09 04:35:19VUE

实现搜索关键词高亮的基本思路

在Vue中实现搜索关键词高亮,主要通过以下步骤完成:

  1. 获取用户输入的搜索关键词
  2. 遍历需要高亮的内容
  3. 使用正则表达式匹配关键词
  4. 将匹配到的关键词替换为带有高亮样式的HTML元素

基础实现方法

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

<script>
export default {
  data() {
    return {
      searchText: '',
      originalContent: '这是一段需要搜索高亮的文本内容'
    }
  },
  computed: {
    highlightedContent() {
      if (!this.searchText) return this.originalContent

      const regex = new RegExp(this.searchText, 'gi')
      return this.originalContent.replace(
        regex,
        match => `<span class="highlight">${match}</span>`
      )
    }
  }
}
</script>

<style>
.highlight {
  background-color: yellow;
  color: black;
}
</style>

处理特殊字符的正则表达式

为了避免搜索内容中包含正则特殊字符导致错误,需要对输入进行转义:

vue实现搜索变色

function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
}

// 在highlightedContent计算属性中使用
const escapedSearchText = escapeRegExp(this.searchText)
const regex = new RegExp(escapedSearchText, 'gi')

多关键词高亮实现

如果需要同时高亮多个关键词,可以扩展实现:

computed: {
  highlightedContent() {
    let result = this.originalContent
    if (!this.searchText) return result

    const keywords = this.searchText.split(' ').filter(k => k.trim())

    keywords.forEach(keyword => {
      const escaped = escapeRegExp(keyword)
      const regex = new RegExp(escaped, 'gi')
      result = result.replace(
        regex,
        match => `<span class="highlight">${match}</span>`
      )
    })

    return result
  }
}

列表项高亮实现

对于列表数据的高亮处理:

vue实现搜索变色

<template>
  <div>
    <input v-model="searchText" />
    <ul>
      <li v-for="(item, index) in filteredList" :key="index" v-html="item.highlighted"></li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      searchText: '',
      items: [
        { text: 'Vue.js框架' },
        { text: 'React框架' },
        { text: 'Angular框架' }
      ]
    }
  },
  computed: {
    filteredList() {
      return this.items.map(item => {
        if (!this.searchText) {
          return { ...item, highlighted: item.text }
        }

        const escaped = escapeRegExp(this.searchText)
        const regex = new RegExp(escaped, 'gi')
        const highlighted = item.text.replace(
          regex,
          match => `<span class="highlight">${match}</span>`
        )

        return { ...item, highlighted }
      })
    }
  }
}
</script>

性能优化建议

对于大数据量的高亮处理,可以考虑以下优化:

  • 使用防抖处理搜索输入
  • 虚拟滚动只渲染可见区域的内容
  • 避免频繁的正则表达式创建
import { debounce } from 'lodash'

export default {
  data() {
    return {
      searchText: '',
      debouncedSearchText: ''
    }
  },
  created() {
    this.debouncedUpdateSearchText = debounce(function(text) {
      this.debouncedSearchText = text
    }, 300)
  },
  watch: {
    searchText(newVal) {
      this.debouncedUpdateSearchText(newVal)
    }
  },
  computed: {
    // 使用debouncedSearchText替代searchText
  }
}

安全注意事项

使用v-html时需要注意XSS攻击风险,确保:

  • 只对可信内容使用v-html
  • 对用户输入进行适当的转义处理
  • 考虑使用DOMPurify等库净化HTML
import DOMPurify from 'dompurify'

// 在高亮函数中使用
return DOMPurify.sanitize(originalContent.replace(regex, ...))

以上实现方法可以根据具体需求进行调整和扩展,核心思路是通过正则匹配和HTML替换实现关键词高亮效果。

标签: vue
分享给朋友:

相关文章

vue查看更多怎么实现

vue查看更多怎么实现

实现 Vue 的“查看更多”功能 数据截取与显示控制 通过 v-if 或 v-show 控制内容的显示与隐藏。初始状态下只显示部分内容,点击“查看更多”后展开完整内容。 <template&g…

vue 实现toast

vue 实现toast

vue 实现 toast 的方法 在 Vue 中实现 Toast 提示功能可以通过多种方式,以下是几种常见的实现方法: 使用第三方库 Vue 生态中有许多成熟的 Toast 库,例如 vue-toa…

vue 指令实现

vue 指令实现

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

vue实现定时

vue实现定时

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

vue实现系统

vue实现系统

Vue 实现系统的核心方法 使用 Vue.js 构建系统时,需结合其响应式特性与组件化开发模式。以下为关键实现路径: 项目初始化与工程配置 通过 Vue CLI 或 Vite 创建项目骨架,推荐选择…

vue 实现图钉

vue 实现图钉

实现图钉效果的步骤 在Vue中实现图钉(固定位置)效果,可以通过CSS的position: sticky属性或监听滚动事件动态修改元素样式。以下是两种常见方法: 方法一:使用CSS的posi…