),结合 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.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>

处理多关键词标记

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

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实现检索内容标记

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