天天看点

vue搜索高亮显示

实现原理:

vue

自定义指令

Vue.directive

效果展示:

vue搜索高亮显示

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)
  }
})

           

使用方法:

继续阅读