🍀简简单单实现关键字高亮匹配指令

核心代码

js 复制代码
export default {
  mounted(el, binding) {
    const { keyword, color = 'yellow' } = binding.value
    if (keyword) {
      const regex = new RegExp(`(${keyword})`, 'gi')
      const originalText = el.textContent
      el.innerHTML = originalText.replace(
        regex,
        `<span style="color: ${color}; font-weight: bold;">$1</span>`
      )
    }
  },
  updated(el, binding) {
    const oldValue = binding.oldValue
    const newValue = binding.value
    const { keyword, color = 'yellow' } = newValue
    if (JSON.stringify(newValue) !== JSON.stringify(oldValue)) {
      if (keyword) {
        const regex = new RegExp(`(${keyword})`, 'gi')
        const originalText = el.textContent
        el.innerHTML = originalText.replace(
          regex,
          `<span style="color: ${color}; font-weight: bold;">$1</span>`
        )
      } else {
        el.innerHTML = el.textContent
      }
    }
  }
}

注册指令

directives.js

js 复制代码
import highKey from './highKey'
export default app => {
  app.directive('highkey', highKey)
}

main.js

js 复制代码
import { createApp } from 'vue'
import App from './App.vue'
import installDirective from '@/directives'

const app = createApp(App)
installDirective(app)

使用

js 复制代码
<template>
<el-card>
  <adminTitle title="高亮关键字" />
  <el-input v-model="keyword" placeholder="输入关键字"></el-input>
  <div style="line-height: 30px;" v-highkey="{ keyword, color: highlightColor }">
    这里是需要高亮匹配关键字的文本内容。你可以输入任意关键字进行测试,看看效果如何。
  </div>
</el-card>
</template>
<script setup>
const keyword = ref('')
const highlightColor = ref('#845EC2')
</script>

效果

相关推荐
千里码aicood几秒前
python+vue智慧物业管理系统设计(源码+文档+调试+基础修改+答疑)
vue.js·spring boot·后端
乐~~~几秒前
解决avue-input-tree组件重置数据不回显/重置失败
前端·javascript·vue.js
你的电影很有趣16 分钟前
lesson68:JavaScript 操作 HTML 元素、属性与样式全指南
开发语言·前端·javascript
妄小闲16 分钟前
html网站源码 html网页模板下载
前端·html
宁雨桥29 分钟前
前端登录加密实战:从原理到落地,守护用户密码安全
前端·安全·状态模式
椒盐螺丝钉42 分钟前
TypeScript类型兼容性
运维·前端·typescript
_JinHao1 小时前
Cesium Viewer对象详解——Cesium基础笔记(快速入门)
前端·javascript·笔记·3d·webgl
正义的大古1 小时前
OpenLayers地图交互 -- 章节十三:拖拽旋转交互详解
javascript·vue.js·openlayers
r0ad1 小时前
从痛点到解决方案:为什么我开发了Chrome元素截图插件
前端·chrome