![](https://i-blog.csdnimg.cn/blog_migrate/489057371ef0acabea7e0d558200ad4d.png)
<template>
<el-input v-model="searchKey" class="w-50 m-2" size="large" placeholder="Please Input" :suffix-icon="Search" @input="changeColor" />
<div>
<div v-for="item in state.contentColor">
<div v-html="item.name"></div>
</div>
</div>
</template>
<script lang="ts" setup>
import { Search } from '@element-plus/icons-vue'
import { reactive, ref } from 'vue'
// 关键词飘红
const searchKey = ref('')
const content = reactive([{ name: '你' }, { name: '你好' }, { name: '好' }, { name: '你好啊' }])
interface Color {
name: string
}
interface Obj {
contentColor: Color[]
}
let state = reactive<Obj>({
contentColor: [],
})
const changeColor = (searchKey: string) => {
if (searchKey === '') {
state.contentColor = []
} else {
let reg = new RegExp(`(${searchKey})`, 'g')
state.contentColor = reactive(
JSON.parse(JSON.stringify(content).replace(reg, `<span style='color:red;'>` + searchKey + `</span>`))
)
}
}
</script>