vue项目一行文本修改关键字颜色(纯借鉴并学习)
需求中需要根据返回的数据和关键字,修改关键字颜色,因为使用v-html怕有漏洞,所以就百度了一个方法,借鉴并记录了下来,只是方便以后自己使用,原地址实在找不到了
上面是要展示的效果,这条文本和关键字是后台返回的,直接上代码~~
一:仅有一个关键字需求修改颜色
下面的代码写成一个单独是文件放在复用的文件夹里,使用的时候就在要使用的页面引入
<script>
export default {
name: 'KeywordText',
props: {
keyword: {
type: String,
default: ''
},
text: {
type: String,
required: true
}
},
render(h) {
const vnodes = [];
const text = this.text.split(this.keyword)
text.forEach(str => {
vnodes.push(h('span', null, str))
vnodes.push(h('span', { style: 'color: #0FBDA0' }, this.keyword))
})
if (text.length > 0) {
vnodes.pop()
}
return h('span', null, vnodes)
}
}
</script>
<!-- 使用 -->
<template>
<div>
<p>
<!-- 在这里传入后台返回的文本数据和关键字就可以了 -->
<changeKeyWord keyword="关键字" text="这一行有一个关键字"> </changeKeyWord>
</p>
<div/>
<template/>
<script>
//引入
import changeKeyWord from '../component/changeKeyword.vue';
<script/>
二:修改多个关键词的颜色
有使用到v-html,因为需要修改的文字是纯展示,所以使用了v-html
//使用
<p class="listTitle">
<span v-html="$options.filters.formatTitle(obj.title,obj.keyWords)"></span>
</p>
<script>
export default {
data(){
return{
obj:{
title:'这是一段文字这是一段123这是一段啦啦',
keyWords:['文字'','123','啦啦'] //这个是后台返回的特殊字符的数组
}
},
filters: {
formatTitle(value, keyword) {
if (!value) return '';
value = value.length > 30 ? value.substr(0, 29) + '...' : value; //标题超过30字符展示...
if (Array.isArray(keyword)) {
keyword.forEach((item) => {
if (item && value.includes(item)) {
var regex = RegExp('(' + item.replace('\\$1') + ')', 'ig');
var html = '<span class="keyWord">' + item + '</span>';
value = value.replace(regex, html)
}
})
} else {
}
return value;
},
}
}
</script>
<style lang='less'>
//写上样式
.keyWord {
color: #0fbda0;
}
</style>