这里直接上代码了,备注都在代码里
<template>
<rich-text :nodes="html"></rich-text>
</template>
<script>
export default {
props: {
content: { // 需要高亮的内容
type: String,
default: ''
},
keys: { // 高亮的关键字,多个用 | 隔开
type: String,
default: ''
},
color: { // 高亮颜色
type: String,
default: '#FD463E'
},
weight: { // 是否加粗
type: Boolean,
default: false
}
},
computed: {
html() {
if (this.keys === '') {
return this.content;
}
var reg = new RegExp((`(${this.keys})`), "gm");
var color = this.color || '#FD463E';
var weight = this.weight ? 'bold' : 'normal';
var replace = '<span style="color:' + color + ';font-weight: ' + weight + ';">$1</span>';
return this.content.replace(reg, replace);
}
},
}
</script>
<style>
</style>
这里封装成了一个组件我在这里命名uni-highlight
使用方法<uni-highlight :content="'大鱼吃小鱼'" :keys="'吃'" :color="'#FF7639'" :weight="true"></uni-highlight>
最后来张效果图吧
如果对你有用,关注一下博主的小程序,登录一下给予支持,以后有什么开源好用的源码都会上传到小程序