当前位置:首页 > VUE

vue实现搜索变色

2026-02-17 16:04:55VUE

实现搜索关键词高亮的方法

在Vue中实现搜索关键词高亮显示,可以通过以下方式实现:

使用v-html指令

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

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

使用计算属性优化

computed: {
  highlightedContent() {
    const searchTerm = this.searchText.trim()
    if (!searchTerm) return this.originalText

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

添加CSS样式

.highlight {
  background-color: yellow;
  font-weight: bold;
  color: #333;
}

安全注意事项

使用v-html时需注意XSS攻击风险,应对输入内容进行转义处理:

methods: {
  escapeHtml(unsafe) {
    return unsafe
      .replace(/&/g, "&amp;")
      .replace(/</g, "&lt;")
      .replace(/>/g, "&gt;")
      .replace(/"/g, "&quot;")
      .replace(/'/g, "&#039;")
  },
  highlightText(text) {
    const safeText = this.escapeHtml(text)
    const safeSearch = this.escapeHtml(this.searchText)
    // ...后续高亮逻辑
  }
}

支持多关键词高亮

如需支持多个关键词高亮显示:

highlightText(text) {
  if (!this.searchText) return text

  const keywords = this.searchText.split(' ').filter(k => k)
  let result = text

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

  return result
}

性能优化建议

对于大量文本内容,考虑使用虚拟滚动技术或分页显示,避免一次性处理过多DOM节点导致性能问题。

vue实现搜索变色

标签: vue
分享给朋友:

相关文章

vue实现录播播放

vue实现录播播放

Vue 实现录播播放 使用 video.js 实现 安装 video.js 和相关的 Vue 适配器: npm install video.js @videojs-player/vue 在 Vue…

vue如何实现到期提醒

vue如何实现到期提醒

实现 Vue 到期提醒功能 使用计算属性计算剩余时间 在 Vue 组件中定义一个计算属性,计算目标日期与当前日期的差值。通过 Date 对象获取时间戳并计算剩余天数或小时数。 computed: {…

vue实现活动倒计时

vue实现活动倒计时

实现活动倒计时的基本思路 在Vue中实现活动倒计时通常需要获取当前时间与活动结束时间的差值,并将其转换为天、小时、分钟、秒的格式展示。通过定时器每秒更新显示的时间。 定义倒计时数据 在Vue组件的d…

vue  select实现

vue select实现

Vue Select 实现方法 在 Vue 中实现下拉选择功能可以使用原生 <select> 标签或第三方库如 vue-select。以下是两种方法的详细说明: 原生 HTML Sele…

vue实现图库

vue实现图库

Vue 实现图库的基本方法 使用 Vue 实现图库功能可以通过多种方式完成,以下是一些常见的方法和实现步骤。 使用 Vue 和第三方库(如 Vue Gallery) 安装 vue-gallery 或…

vue实现遮罩

vue实现遮罩

Vue 实现遮罩层的方法 在 Vue 中实现遮罩层可以通过多种方式完成,以下是几种常见的方法: 方法一:使用 v-show 或 v-if 控制显示 通过 Vue 的指令动态控制遮罩层的显示与隐藏。…