核心代码
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>
效果
