当前位置:首页 > VUE

vue实现高亮显示

2026-01-19 13:44:04VUE

Vue 实现高亮显示的方法

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

使用 v-html 和字符串替换

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

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

基于组件的高亮方案

创建可复用的高亮组件:

<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 预约页面实现步骤 准备工作 安装Vue CLI创建项目,确保已配置好开发环境。使用vue create appointment-page初始化项目,选择默认配置或手动配置。 页面结构设计 在…

vue实现图片搜索

vue实现图片搜索

Vue实现图片搜索功能 使用HTML5的File API获取图片 通过<input type="file">元素让用户选择图片文件,使用FileReader对象读取图片数据。 <…

vue实现tab换行

vue实现tab换行

Vue实现Tab切换的常见方法 使用Vue实现Tab切换功能可以通过多种方式完成,以下是几种常见的方法: 动态组件结合v-if或v-show 通过v-if或v-show控制不同Tab内容的显示与隐…

vue手写签名如何实现

vue手写签名如何实现

实现手写签名的基本思路 在Vue中实现手写签名功能,通常需要借助HTML5的Canvas API来捕获用户的绘制操作。核心流程包括初始化画布、监听触摸/鼠标事件、记录轨迹以及生成签名图片。…

vue实现下载暂停

vue实现下载暂停

Vue实现下载暂停功能 在Vue中实现下载暂停功能,通常需要结合XMLHttpRequest或Fetch API的AbortController来控制请求中断。以下是具体实现方法: 使用XMLH…

vue实现div

vue实现div

Vue 实现 DIV 元素的方法 在 Vue 中实现 DIV 元素可以通过多种方式,以下是几种常见的实现方法: 使用模板语法 在 Vue 的模板中直接使用 HTML 的 <div> 标签…