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

核心代码

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>

效果

相关推荐
Mintopia9 分钟前
静态内容页该用HTML还是Next.js展示更好
前端·html·next.js
LYFlied16 分钟前
【每日算法】LeetCode 226. 翻转二叉树
前端·算法·leetcode·面试·职场和发展
无名无姓某罗17 分钟前
jQuery 请求 SpringMVC 接口返回404错误排查
前端·spring·jquery
霁月的小屋21 分钟前
Vue响应式数据全解析:从Vue2到Vue3,ref与reactive的实战指南
前端·javascript·vue.js
李少兄25 分钟前
深入理解 Java Web 开发中的 HttpServletRequest 与 HttpServletResponse
java·开发语言·前端
holidaypenguin27 分钟前
antd 5 + react 18 + vite 7 升级
前端·react.js
小满zs29 分钟前
Next.js第十五章(Image)
前端·next.js
tangbin58308530 分钟前
iOS Swift 可选值(Optional)详解
前端·ios
孟祥_成都32 分钟前
nest.js / hono.js 一起学!日志功能/统一返回格式/错误处理
前端·node.js
_膨胀的大雄_36 分钟前
01-创建型模式
前端·设计模式