当前位置:首页 > VUE

vue实现高亮

2026-03-07 00:57:13VUE

Vue实现文本高亮的几种方法

在Vue中实现文本高亮可以通过多种方式完成,以下是几种常见的方法:

使用v-html指令

通过将需要高亮的文本替换为HTML标签,再使用v-html渲染:

<template>
  <div v-html="highlightedText"></div>
</template>

<script>
export default {
  data() {
    return {
      originalText: '这是一个需要高亮的文本',
      keyword: '高亮'
    }
  },
  computed: {
    highlightedText() {
      const regex = new RegExp(this.keyword, '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 keyword = binding.value
    const regex = new RegExp(keyword, 'gi')
    el.innerHTML = text.replace(regex, match => 
      `<span style="background-color: yellow">${match}</span>`
    )
  }
})

// 使用方式
<template>
  <div v-highlight="keyword">{{ originalText }}</div>
</template>

使用组件封装

创建一个专门的高亮组件,更易于维护:

<template>
  <span>
    <template v-for="(part, index) in parts">
      <span v-if="part.highlight" :key="index" class="highlight">
        {{ part.text }}
      </span>
      <span v-else :key="index">
        {{ part.text }}
      </span>
    </template>
  </span>
</template>

<script>
export default {
  props: {
    text: String,
    keyword: String
  },
  computed: {
    parts() {
      if (!this.keyword) return [{ text: this.text, highlight: false }]

      const regex = new RegExp(this.keyword, 'gi')
      const parts = []
      let lastIndex = 0
      let match

      while ((match = regex.exec(this.text)) !== null) {
        if (match.index > lastIndex) {
          parts.push({
            text: this.text.slice(lastIndex, match.index),
            highlight: false
          })
        }

        parts.push({
          text: match[0],
          highlight: true
        })

        lastIndex = match.index + match[0].length
      }

      if (lastIndex < this.text.length) {
        parts.push({
          text: this.text.slice(lastIndex),
          highlight: false
        })
      }

      return parts
    }
  }
}
</script>

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

使用第三方库

可以使用专门的高亮库如mark.js:

npm install mark.js

// 组件中使用
<template>
  <div ref="content">
    {{ content }}
  </div>
</template>

<script>
import Mark from 'mark.js'

export default {
  data() {
    return {
      content: '需要高亮的文本内容',
      keyword: '高亮'
    }
  },
  watch: {
    keyword(newVal) {
      this.highlightText(newVal)
    }
  },
  methods: {
    highlightText(keyword) {
      const instance = new Mark(this.$refs.content)
      instance.unmark()
      if (keyword) {
        instance.mark(keyword, {
          className: 'highlight'
        })
      }
    }
  },
  mounted() {
    this.highlightText(this.keyword)
  }
}
</script>

性能优化建议

对于大量文本的高亮操作,建议使用虚拟滚动或分页加载技术,避免一次性处理过多DOM节点影响性能。

动态高亮时,使用防抖或节流技术减少高频操作带来的性能开销:

vue实现高亮

import { debounce } from 'lodash'

methods: {
  highlightText: debounce(function(keyword) {
    // 高亮逻辑
  }, 300)
}

安全注意事项

使用v-html时要特别注意XSS攻击风险,确保高亮的内容来自可信源,或对输入内容进行适当的转义和过滤。

标签: vue高亮
分享给朋友:

相关文章

vue compile 实现

vue compile 实现

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

自实现vue

自实现vue

实现 Vue 的核心功能 要实现一个简化版的 Vue,需要理解其核心功能:数据响应式、模板编译、虚拟 DOM 和组件系统。以下是关键步骤的分解: 数据响应式 Vue 使用 Object.define…

vue实现分站

vue实现分站

Vue 实现分站的方案 在 Vue 中实现分站功能通常涉及路由配置、环境变量管理和动态加载资源。以下是几种常见的实现方式: 基于路由的分站实现 通过 Vue Router 配置多路由,区分不同站点的…

vue实现录音

vue实现录音

Vue 实现录音功能 在 Vue 中实现录音功能可以通过浏览器提供的 MediaRecorder API 完成。以下是具体实现方法: 引入依赖 确保项目支持现代浏览器 API,无需额外安装库…

node vue实现

node vue实现

Node.js 与 Vue.js 实现方案 环境搭建 安装 Node.js(建议 LTS 版本),通过 npm 或 yarn 初始化项目。Vue.js 可通过 Vue CLI 快速搭建: npm…

vue 水印 实现

vue 水印 实现

Vue 水印实现方法 使用 canvas 动态生成水印 在 Vue 组件中通过 canvas 绘制水印,并将其作为背景图片插入到目标元素中。这种方法灵活性高,支持动态调整水印内容、角度和透明度。 &…