搜索关键词高亮 vue
1.背景
给搜索出来的相应的字符串,加上高亮显示。
2.思路分析
2.1.建立函数wrapperKeyword,传入两个参数
listQuery为搜索的数据(数据结构为对象{}),其中包括title,author等字段属性
methods:{ wrapperKeyword(k,v){ function highlight(value){ return `${value}` } if(!this.listQuery[k]){ return v }else{ return v.replace( new RegExp(this.listQuery[k],'ig'), v=>highlight(v) ) } } }
wrapperKeyword函数返回的是带有html格式的字符串,所以在html中,使用v-html
2.2.引用wrapperKeyword函数
mounted(){ this.list.forEach( book => { book.titleWrapper = this.wrapperKeyword("title", book.title) book.authorWrapper = this.wrapperKeyword("author", book.author) }) },
2.3.data数据
data () { return { list:[ {tite:'this is title1',author:'this is author1',content:'this is content1'}, {tite:'this is title2',author:'this is author2',content:'this is content2'}, {tite:'this is title3',author:'this is author3',content:'this is content3'}, {tite:'this is title4',author:'this is author4',content:'this is content4'}, ], listQuery: {title: "is",author: "is"}
};
},
2.4.html部分
<div v-for="(item, index) in list" :key="index"> <span v-html="item.titleWrapper">这里是题目span> <span v-html="item.authorWrapper">这里是题目span> div>