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

核心代码

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>

效果

相关推荐
peachSoda738 分钟前
封装一个不同跳转方式的通用方法(跳转外部链接,跳转其他小程序,跳转半屏小程序)
前端·javascript·微信小程序·小程序
@PHARAOH1 小时前
HOW - 浏览器兼容(含 Safari)
前端·safari
undefined在掘金390411 小时前
flutter 仿商场_首页
前端
少卿1 小时前
react-native图标替换
前端·react native
熊猫钓鱼>_>1 小时前
TypeScript前端架构与开发技巧深度解析:从工程化到性能优化的完整实践
前端·javascript·typescript
敲敲敲敲暴你脑袋1 小时前
Canvas绘制自定义流动路径
vue.js·typescript·canvas
JYeontu2 小时前
肉眼难以分辨 UI 是否对齐,写个插件来辅助
前端·javascript
fox_2 小时前
别再踩坑!JavaScript的this关键字,一次性讲透其“变脸”真相
前端·javascript
盛夏绽放2 小时前
uni-app Vue 项目的规范目录结构全解
前端·vue.js·uni-app
少卿2 小时前
React Native Vector Icons 安装指南
前端·react native