前段时间有一个需求,需要在全局检索的时候,将搜索的文字在展示列表中高亮,并通过不同的颜色显示出来
下面的demo是通过vue3.0来实现:
- 首先通过eval将字符串当做 JavaScript 代码进行执行,使正则传入变量进行解析
- replace将正则匹配到的数据,替换成可编译的标签,标签内部加入想要高亮显示的颜色
<script lang="ts">
import { defineComponent,onMounted,ref } from 'vue'
export default defineComponent({
setup() {
const text = ref("如果有一天,天空消散于无尽的宇宙")
onMounted(() => {
let str = "一天"
text.value=text.value.replace(eval("/"+str+"/g"),`<span style="color:red">${str}</span>`)
console.log(text.value)
})
return{
text
}
}
})
</script>
- 通过v-html解析带html标签的数据
<template>
<div v-html="text"></div>
</template>
编译后的效果如下图所示: