<template>
<div v-html="highLight(text)" @click="handleClick">{{text}}</div>
</<template>>
<script>
data() {
return {
text: '123456'
}
},
methods: {
highLight(title){
// 如果标题中包含,关键字就替换一下
const searchWord = 1
if(title.includes(searchWord)){
title = title.replace(
searchWord,
// 这里是替换成html格式的数据,最好再加一个样式权重,保险一点
'<span style="color:red!important;"">'+ searchWord +'</span>'
)
return title
}
// 不包含的话还用这个
else{
return title
}
},
handleClick(e) {
if (e.target.localName.toLowerCase() === 'span') {
console.log('点击了高亮文字');
}
},
}
</script
字符串某个文字高亮,且可以点击(v-html点击事件无效)
最新推荐文章于 2024-08-14 13:53:45 发布