当前位置:首页 > VUE

vue实现搜索文字变色

2026-02-24 23:01:29VUE

实现搜索文字变色的方法

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

方法一:使用v-html和正则表达式替换

vue实现搜索文字变色

<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>

方法三:使用组件封装

vue实现搜索文字变色

创建一个可重用的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>

使用方法:

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

注意事项

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

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

相关文章

vue实现3d宇宙

vue实现3d宇宙

Vue实现3D宇宙效果 使用Three.js库 Three.js是一个强大的JavaScript 3D库,可以轻松集成到Vue项目中。安装Three.js依赖: npm install three…

vue实现打印二维码

vue实现打印二维码

安装二维码生成库 使用 qrcode 或 vue-qrcode 库生成二维码。通过 npm 安装: npm install qrcode vue-qrcode 生成二维码 在 Vue 组…

vue 实现递归

vue 实现递归

Vue 实现递归组件的方法 在 Vue 中实现递归组件通常用于处理树形结构数据,例如菜单、评论列表或文件目录。以下是实现递归组件的关键步骤: 定义递归组件 递归组件需要设置 name 属性,以便在…

vue实现类别

vue实现类别

Vue 实现类别的几种方法 在 Vue 中实现类别功能可以通过多种方式完成,以下是一些常见的方法: 使用 v-bind:class 动态绑定类名 通过对象语法或数组语法动态绑定类名,根据条件添加或…

vue compile 实现

vue compile 实现

Vue 编译实现原理 Vue 的编译过程将模板字符串转换为渲染函数,主要分为解析、优化和代码生成三个阶段。 解析阶段(Parse) 将模板字符串转换为抽象语法树(AST)。Vue 使用正则表达式和有…

vue实现fadein

vue实现fadein

Vue 实现 FadeIn 效果 在 Vue 中实现淡入(FadeIn)效果可以通过 CSS 过渡、动画或第三方库实现。以下是几种常见方法: 使用 CSS 过渡 通过 Vue 的过渡系统结合 CSS…