当前位置:首页 > VUE

vue实现高亮显示

2026-01-19 13:44:04VUE

Vue 实现高亮显示的方法

在 Vue 中实现高亮显示通常涉及文本匹配和样式动态切换。以下是几种常见实现方式:

使用 v-html 和字符串替换

通过替换目标文本为带样式的 HTML 实现高亮:

vue实现高亮显示

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

<script>
export default {
  data() {
    return {
      originalText: 'This is a sample text for highlighting',
      searchTerm: 'sample'
    }
  },
  computed: {
    highlightedText() {
      return this.originalText.replace(
        new RegExp(this.searchTerm, 'gi'),
        match => `<span class="highlight">${match}</span>`
      )
    }
  }
}
</script>

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

使用自定义指令

创建可复用的高亮指令:

Vue.directive('highlight', {
  inserted(el, binding) {
    const text = el.textContent
    const term = binding.value
    const regex = new RegExp(term, 'gi')
    el.innerHTML = text.replace(regex, match => 
      `<span style="background-color: yellow">${match}</span>`
    )
  }
})

// 使用方式
<div v-highlight="'search term'">Some text containing search term</div>

基于组件的高亮方案

创建可复用的高亮组件:

vue实现高亮显示

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

<script>
export default {
  props: ['text', 'query'],
  computed: {
    parts() {
      const regex = new RegExp(`(${this.query})`, 'gi')
      return this.text.split(regex).map(part => ({
        text: part,
        highlight: regex.test(part)
      }))
    }
  }
}
</script>

使用第三方库

考虑使用专门的高亮库如 mark.js

npm install mark.js

// 组件中使用
import Mark from 'mark.js'

export default {
  methods: {
    highlight() {
      const instance = new Mark(this.$refs.highlightContainer)
      instance.mark(this.searchTerm, {
        className: 'highlight'
      })
    }
  },
  mounted() {
    this.highlight()
  }
}

动态样式绑定

对于简单场景可使用动态 class 绑定:

<template>
  <span :class="{ 'text-yellow': shouldHighlight }">
    {{ text }}
  </span>
</template>

<script>
export default {
  props: ['text', 'shouldHighlight']
}
</script>

每种方法适用于不同场景,v-html 方案适合简单替换,自定义指令提供更好的复用性,组件方案更灵活,第三方库适合复杂高亮需求。注意使用 v-html 时需防范 XSS 风险,对用户输入内容进行适当过滤。

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

相关文章

vue 实现回复

vue 实现回复

Vue 实现回复功能 在 Vue 中实现回复功能通常涉及表单提交、数据绑定和列表渲染。以下是实现步骤和代码示例: 数据绑定与表单 <template> <div>…

vue实现RTMP

vue实现RTMP

Vue 中实现 RTMP 流播放 RTMP(Real-Time Messaging Protocol)是一种用于实时音视频流传输的协议。在 Vue 中实现 RTMP 播放通常需要借助第三方库或播放器。…

vue实现反馈

vue实现反馈

Vue 实现反馈功能的方法 在 Vue 中实现反馈功能可以通过多种方式,包括弹窗提示、Toast 消息、表单提交等。以下是几种常见的实现方法。 弹窗反馈 使用 Vue 的组件化特性创建一个弹窗组件,…

vue实现gridlayout

vue实现gridlayout

Vue 实现 Grid Layout 使用 CSS Grid 布局 CSS Grid 是一种强大的布局系统,可以直接在 Vue 组件的样式中使用。通过定义网格容器和网格项,可以快速实现复杂的布局结构。…

vue实现字幕

vue实现字幕

Vue 实现字幕功能 在 Vue 中实现字幕功能可以通过动态绑定数据和 CSS 动画来实现。以下是具体实现方法: 1. 基础字幕组件 创建一个字幕组件,通过 v-model 或 props 接收字…

vue实现搜索查询

vue实现搜索查询

Vue 实现搜索查询的方法 双向绑定实现实时搜索 在Vue中可以通过v-model绑定输入框的值,结合计算属性或watch监听输入变化实现实时搜索。 <template> <i…