思路:通过正则RegExp进行全局匹配,将符合条件的元素通过replace替换成为HTML代码片段
封装成自定义指令在main.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)
}
})
使用:引入该指令,然后使用方法如下
关键字为变量
v-hightlight:[文本]="关键字"