),结合 Vu…">
当前位置:首页 > VUE

vue实现检索内容标记

2026-01-07 02:31:14VUE

Vue 实现检索内容标记的方法

使用 v-html 和字符串替换

通过检索关键词,在文本中使用字符串替换方法添加标记标签(如 <span class="highlight">),结合 Vue 的 v-html 指令渲染带标记的内容。

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

<script>
export default {
  data() {
    return {
      originalText: '这里是需要检索的原始文本内容',
      searchKeyword: '检索'
    };
  },
  computed: {
    highlightedText() {
      const regex = new RegExp(this.searchKeyword, 'gi');
      return this.originalText.replace(
        regex,
        match => `<span class="highlight">${match}</span>`
      );
    }
  }
};
</script>

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

使用自定义指令

创建一个自定义指令 v-highlight,自动处理文本标记逻辑,提高代码复用性。

vue实现检索内容标记

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 class="highlight">${match}</span>`
    );
  }
});
<template>
  <div v-highlight="searchKeyword">{{ originalText }}</div>
</template>

处理多关键词标记

支持同时标记多个关键词,通过数组传递关键词并循环处理。

vue实现检索内容标记

computed: {
  highlightedText() {
    let result = this.originalText;
    this.keywords.forEach(keyword => {
      const regex = new RegExp(keyword, 'gi');
      result = result.replace(
        regex,
        match => `<span class="highlight">${match}</span>`
      );
    });
    return result;
  }
}

使用第三方库

考虑使用专门的高亮库如 mark.js,集成到 Vue 项目中实现更复杂的高亮效果。

import Mark from 'mark.js';

export default {
  methods: {
    highlightText() {
      const marker = new Mark(document.getElementById('content'));
      marker.mark(this.searchKeyword, {
        className: 'highlight'
      });
    }
  },
  mounted() {
    this.highlightText();
  }
};

性能优化建议

对于大文本内容,使用防抖(debounce)技术延迟高亮操作,避免频繁重绘影响性能。

import { debounce } from 'lodash';

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

以上方法可根据具体需求选择或组合使用,实现灵活高效的检索内容标记功能。

标签: 标记内容
分享给朋友:

相关文章

vue实现点击切换内容

vue实现点击切换内容

使用v-if/v-else指令实现切换 通过Vue的v-if和v-else指令可以轻松实现内容切换。定义一个布尔变量控制显示状态,点击事件切换该变量值。 <template> <…

react如何获取节点内容

react如何获取节点内容

获取节点内容的常用方法 使用 ref 获取 DOM 节点 在 React 中,可以通过 useRef 或 createRef 创建 ref 对象,并将其附加到目标元素上。通过 ref 的 curren…

react中如何获取结点内容

react中如何获取结点内容

获取DOM节点内容的方法 在React中获取DOM节点内容通常通过ref实现,以下是几种常见方式: 使用useRef Hook(函数组件) import { useRef } from 'rea…

react如何获取可编辑div的内容

react如何获取可编辑div的内容

获取可编辑 div 内容的方法 在 React 中获取可编辑 div(通过 contentEditable 属性实现)的内容,可以通过以下几种方式实现: 使用 onInput 或 onBlur 事件…

js实现长按显示内容

js实现长按显示内容

实现长按显示内容的方法 使用JavaScript实现长按显示内容的功能,可以通过监听mousedown、touchstart、mouseup、touchend等事件来实现。以下是具体实现方法: 监听…

js实现内容切换

js实现内容切换

使用innerHTML切换内容 通过修改DOM元素的innerHTML属性实现内容切换。这种方法适合简单的文本或HTML片段替换。 const element = document.getEleme…