实现原理:vue
的自定义指令
Vue.directive
效果展示:
js部分:
import Vue from 'vue'
function hightLight (el, binding) {
const match = binding.value
const reg = new RegExp(match, 'g')
const txt = binding.arg
let str = ''
if (txt) {
str = txt.replace(reg, `<span style="color:red">${match}</span>`)
} else {
str = ''
}
el.innerHTML = str
}
Vue.directive('hightlight', {
bind (el, binding) {
hightLight(el, binding)
},
componentUpdated (el, binding) {
hightLight(el, binding)
}
})
使用方法:
<div class="title" v-hightlight:[你的数据]="希望高亮的文本"></div>