vue3-highlight组件实现

  |  

prop设计

text: 需要渲染的文本, string类型

keywords: 关键字, string类型

color: 高亮的颜色, string类型

代码实现

<template>
<p>
<span
v-for="(item, index) in arr"
:key="index"
:style="{color: item.highlight ? props.color : (props.defaultColor || '#000')}"
>
{{ item.text }}
</span>
</p>
</template>
<script lang="ts" setup>
import {ref, reactive, toRef} from "vue"

const props = defineProps<{text: string; keyword: string; color: string, defaultColor?: string}>()

const styleObj = ref<{color: string}>({color: ""})

styleObj.value.color = toRef(props, "value").value

const arr = reactive(splitKeyWord(props.text, props.keyword))

/**
* @description 通过关键字将文本分割
* @return Array<{text: string, highlight: boolean}>
*/
function splitKeyWord(str: string, keyword: string) {
const res = []
//如果包含关键字
if (str.indexOf(keyword) > -1) {
const arr = str.split(keyword)
const len = arr.length
for (let i = 0; i < len; i++) {
if (arr[i] !== "") {
res.push({text: arr[i], highlight: false})
}
res.push({text: keyword, highlight: true})
}
res.pop()
} else {
res.push({text: str, highlight: false})
}
return res
}
</script>

多个keyword和color

需要多个keyword和color时,props对应接受的数据需要改为数组的形式

同时需要遍历keywords将 需要渲染的每一项改造成

{
text: string,
highlight: boolean,
color: string
}

然后style中指定对应的颜色

×

纯属好玩

扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

文章目录
  1. 1. prop设计
  2. 2. 代码实现
  3. 3. 多个keyword和color
,