1.背景
给搜索出来的相应的字符串,加上高亮显示。
2.思路分析
2.1.建立函数wrapperKeyword,传入两个参数
listQuery为搜索的数据(数据结构为对象{}),其中包括title,author等字段属性
methods:{ wrapperKeyword(k,v){ function highlight(value){ return `<span style="color: #1890ff;">${value}</span>` } 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>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构