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

核心代码

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>

效果

相关推荐
道友可好17 分钟前
AI 是最好的混乱放大器:代码熵管理实战
前端·人工智能·后端
猩猩程序员1 小时前
前端学习 AI Agent 开发
前端
Younglina2 小时前
打了3年羽毛球球才发现:我对自己的装备和胜率一无所知
前端·后端
风骏时光牛马2 小时前
Bash脚本高阶实战与常见报错完整代码案例详解
前端
kartjim2 小时前
我用 AI 一小时写了一个世界杯数据可视化平台|前端 VibeCoding 初体验
前端·程序员·ai编程
lichenyang4532 小时前
从一个 WebView Demo 开始,理解 ASCF 小程序底座到底在做什么
前端
牧艺2 小时前
用 Next.js 搭建 AI Agent 前端编排:从 Plan 到 SSE Trace 的完整实践
前端·agent
行者全栈架构师2 小时前
UniApp集成vk-uview-ui组件库详解:打造高效UI开发体验
前端·vue.js
林希_Rachel_傻希希2 小时前
js里面的proxy理解。以及vue3响应式数据设计底层
前端·javascript·面试
sunrains2 小时前
uniapp x 动态Tabbar(切换无闪烁)+动角标+主题切换+自定义tabbar页面导航栏样式设置 支持服务端动态配置根据角色动态设置Tabbar
前端