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>
相关推荐
Laravel技术社区13 分钟前
用PHP8实现斗地主游戏,实现三带一,三带二,四带二,顺子,王炸功能(第二集)
前端·游戏·php
m0_738120721 小时前
应急响应——知攻善防Web-3靶机详细教程
服务器·前端·网络·安全·web安全·php
程序员爱钓鱼8 小时前
Node.js 编程实战:文件读写操作
前端·后端·node.js
PineappleCoder8 小时前
工程化必备!SVG 雪碧图的最佳实践:ID 引用 + 缓存友好,无需手动算坐标
前端·性能优化
JIngJaneIL9 小时前
基于springboot + vue古城景区管理系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot·后端
敲敲了个代码9 小时前
隐式类型转换:哈基米 == 猫 ? true :false
开发语言·前端·javascript·学习·面试·web
澄江静如练_9 小时前
列表渲染(v-for)
前端·javascript·vue.js
JustHappy10 小时前
「chrome extensions🛠️」我写了一个超级简单的浏览器插件Vue开发模板
前端·javascript·github
Loo国昌10 小时前
Vue 3 前端工程化:架构、核心原理与生产实践
前端·vue.js·架构