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

核心代码

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>

效果

相关推荐
OpenTiny社区几秒前
操作ArkTS页面跳转及路由相关心得
前端·typescript·web·opentiny
xiaohua0708day1 分钟前
Lodash库
前端·javascript·vue.js
huakoh1 分钟前
Claude Code 从零到上手指南:国产工具链复现80% Agent能力,DeepSeek+LangChain实战
前端
Ankkaya4 分钟前
浏览器插件接入 Google 登录
前端
Asmewill5 分钟前
DeepAgents学习笔记一(构建深度多智能体)
前端
万物皆对象6666 分钟前
切换路由时页面空白问题(vue3)
前端·vue.js·typescript
突然好热6 分钟前
TS 调试技巧
前端·javascript·typescript
h64648564h8 分钟前
Flutter 国际化(i18n)全指南:一键切换中/英/日多语言
前端·javascript·flutter
令人头秃的代码0_08 分钟前
AI时代下,如何做原子代码拆分
前端
我材不敲代码1 小时前
Python 函数核心:位置参数与关键字参数详解
java·前端·python