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>