/*
联想建议
*/
<template>
<div class="searchSuggestionMain">
<van-cell v-for="(item, index) in suggestionsList" :key="index" icon="search" clickable>
<div slot="title" v-html="heightlight(item.content)"></div>
</van-cell>
<!-- {{}}绑定=>纯文本Hello <span style="color:red">World</span> -->
<div>{{ htmlStr }}</div>
<!-- v-html指令 -->
<div v-html="htmlStr"></div>
</div>
</template>
<script>
export default {
name: 'SearchSuggestion',
props: {
searchText: {
type: String,
required: true
}
},
data() {
return {
suggestionsList: [],
htmlStr: 'Hello <span style="color:red">World</span>'
}
},
methods: {
// 高亮函数
heightlight(text) {
// 动态变量创建正则
/*
RegExp正则构造函数
参数一:匹配模式字符串
参数二:匹配模式,gi全局忽略大小写
*/
//const reg = new RegExp(this.searchText, 'gi')
//return text.replace(reg, `<span class="active">${this.searchText}</span>`)
var reg = new RegExp(this.searchText, "gi");
text = text.replace(reg, function (txt) {
return `<span class="active">`+txt+`</span>`;
})
return text;
},
}
}
</script>
<style scoped lang="less">
/deep/ span.active {
color: #3296fa !important;
}
</style>
前端实现搜索关键字高亮功能:
于 2022-08-15 15:01:35 首次发布