一、directives简介
简介可以参考官方文档地址为:
https://cn.vuejs.org/guide/reusability/custom-directives.html#directive-hooks
二、实现步骤
//html中
<div class="chat-record" v-highlight:content="keyWord">
{{content}}
</div>
//script中
// 关键词keyword高亮
directives: {
highlight: {
bind(el, binding) {
const keyWord = binding.value;
if(keyWord){
const regex = new RegExp(keyWord, "gi");
const content = el.textContent;
el.innerHTML = content.replace(
regex,
'<span class="highlight">$&</span>'
);
}
},
update(el, binding) {
const keyWord = binding.value;
if(keyWord){
const regex = new RegExp(keyWord, "gi");
const content = el.textContent;
el.innerHTML = content.replace(
regex,
'<span class="highlight">$&</span>'
);
}
},
},
}
//style中
.highlight {
color: #2878ff;
}