vue2自定义指令directive用法: dom中关键字文字高亮

vue2自定义指令directive: 关键字文字高亮

大概是这样的效果,具体看请参考下面的写法:

一、步骤 1: 编写自定义指令文件

确保你的自定义指令逻辑能够正确处理从变量中传递的值。指令的实现不需要更改,因为它已经支持动态传递高亮文本。

创建js文件:highlight.js

javascript 复制代码
export default {
  inserted: function (el, binding) {
    highlightText(el, binding.value, binding.arg || 'highlight');
  },
  update: function (el, binding) {
    highlightText(el, binding.value, binding.arg || 'highlight');
  }
};

function highlightText(element, textToHighlight, highlightClass) {
  const walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT);
  let node;
  
  // 先移除之前的高亮
  const highlights = element.querySelectorAll(`.${highlightClass}`);
  highlights.forEach(highlight => {
    const parent = highlight.parentNode;
    parent.replaceChild(document.createTextNode(highlight.textContent), highlight);
    parent.normalize();
  });
  
  // 添加新的高亮
  while ((node = walker.nextNode())) {
    const text = node.nodeValue;
    const regex = new RegExp(textToHighlight, 'gi');
    const newHTML = text.replace(regex, match => 
      `<span class="${highlightClass}">${match}</span>`
    );
    
    if (newHTML !== text) {
      const temp = document.createElement('span');
      temp.innerHTML = newHTML;
      node.parentNode.replaceChild(temp, node);
    }
  }
}

二、步骤 2: 在main.js中引入指令

确保指令在main.js中已正确引入和注册。

javascript 复制代码
import Vue from 'vue';
import App from './App.vue';

import highlightDirective from './highlight'; // 确保路径正确
// 注册全局指令
Vue.directive('highlight', highlightDirective);

new Vue({
  render: h => h(App),
}).$mount('#app');

三、步骤 3: 在组件中定义变量

首先,在组件中定义一个变量,用于存储需要高亮的文本。

javascript 复制代码
<template>
  <div v-highlight="highlightText" class="content">
    这里是一些包含个人信息的文本,个人信息需要被高亮显示。
  </div>
</template>
 
<script>
export default {
  name: 'HighlightExample',
  data() {
    return {
      highlightText: '个人信息' // 定义需要高亮的文本
    };
  }
}
</script>
 
<style>
.highlight {
  background-color: yellow;
  font-weight: bold;
}
</style>
相关推荐
中微子3 小时前
🔥 React Context 面试必考!从源码到实战的完整攻略 | 99%的人都不知道的性能陷阱
前端·react.js
中微子4 小时前
React 状态管理 源码深度解析
前端·react.js
加减法原则5 小时前
Vue3 组合式函数:让你的代码复用如丝般顺滑
前端·vue.js
yanlele6 小时前
我用爬虫抓取了 25 年 6 月掘金热门面试文章
前端·javascript·面试
lichenyang4536 小时前
React移动端开发项目优化
前端·react.js·前端框架
你的人类朋友6 小时前
🍃Kubernetes(k8s)核心概念一览
前端·后端·自动化运维
web_Hsir6 小时前
vue3.2 前端动态分页算法
前端·算法
烛阴7 小时前
WebSocket实时通信入门到实践
前端·javascript
草巾冒小子7 小时前
vue3实战:.ts文件中的interface定义与抛出、其他文件的调用方式
前端·javascript·vue.js
DoraBigHead7 小时前
你写前端按钮,他们扛服务器压力:搞懂后端那些“黑话”!
前端·javascript·架构