之前對文本進行高亮總是需要一些很多操作,但是使用了指令之後,就會發現變得很簡單
// 註冊指令
Vue.directive('highlight', {
// 這裏的 el 就是被註冊指令的 node 節點, binding 就是節點信息,
// 包括一個 value,就是傳進來的數據
// vnode 就是 vue 虛擬節點
// 剛剛註冊這個事件,就使用 bind
bind(el, binding, vnode) {
const {
value
} = binding;
if (value && typeof value === 'object') {
const {hWord, word} = value;
el.innerHTML = word.replace(new RegExp(hWord, 'ig'), (a) => {
return `<span class="height-light">${a}</span>`
});
}
},
// 綁定的數據更新了,執行 update
update(el, binding, vnode) {
const {
value
} = binding;
if (value && typeof value === 'object') {
const {hWord, word} = value;
el.innerHTML = word.replace(new RegExp(hWord, 'ig'),
(a) => `<span class="height-light">${a}</span>` );
}
}
});
<!-- 使用指令 由於 css 過於簡單,這裏就不寫了 -->
<div v-if="showSearchList.length > 0">
<div class="custom-search-list-bar"
:key="item.label"
@click="handleTo(item)"
v-for="item in showSearchList">
<div class="custom-search-title" v-highlight="{hWord: searchv, word: item.label}">
<span class="custom-cell-text"></span>
</div>
</div>
</div>
使用方法 就是 v-heighlight