基于Vue实现关键词实时搜索高亮显示关键词 |
您所在的位置:网站首页 › qq浏览器设置高亮词 › 基于Vue实现关键词实时搜索高亮显示关键词 |
最近在做移动real-time-search于实时搜索和关键词高亮显示的功能,通过博客的方式总结一下,同时希望能够帮助到别人~~~ 如果不喜欢看文字的朋友我写了一个demo方便已经上传到了github上,可以clone下来直接看代码 https://github.com/IT0315/real-time-search.git 好了闲话不多说直接上代码 实时搜索实时搜索通过触发input事件和定时器来实现 在每次输入框的值变化的时候都会执行handleQuery方法 clearTimer () { if (this.timer) { clearTimeout(this.timer) } }, handleQuery (event) { this.clearTimer() console.log(event.timeStamp) this.timer = setTimeout(() => { console.log(event.timeStamp) // console.log(this.lastTime) // if (this.lastTime - event.timeStamp === 0) { this.$http.post('/api/vehicle').then(res => { console.log(res.data.data) this.changeColor(res.data.data) }) // } }, 2000) },
注意:如果时间设置过短或者说我们服务器请求较慢的话,可能第一次查询还没有返回便进行了第二次查询,那么返回的数据将是两次查询的结果,造成查询结果的混乱,如果使用的是axios可以利用axios.CancelToken来终止上一次的异步请求,防止旧关键字查询覆盖新输入的关键字查询结果。 高亮显示通过RegExp实现对关键词的替换,通过添加class实现关键词高亮显示 changeColor (resultsList) { resultsList.map((item, index) => { // console.log('item', item) if (this.keyWords && this.keyWords.length > 0) { // 匹配关键字正则 let replaceReg = new RegExp(this.keyWords, 'g') // 高亮替换v-html值 let replaceString = '' + this.keyWords + '' resultsList[index].name = item.name.replace( replaceReg, replaceString ) } }) this.results = [] this.results = resultsList }在查询到结果后执行changeColor方法将查询出来的数据传递过来通过RegExp来将关键词替换成huml标签,同时用vue中的v-html进行绑定。 最后将demo完整的代码展示出来 export default { name: 'Home', data () { return { keyWords: '', results: [] } }, methods: { clearTimer () { if (this.timer) { clearTimeout(this.timer) } }, handleQuery (event) { this.clearTimer() console.log(event.timeStamp) this.timer = setTimeout(() => { console.log(event.timeStamp) // console.log(this.lastTime) // if (this.lastTime - event.timeStamp === 0) { this.$http.post('/api/vehicle').then(res => { console.log(res.data.data) this.changeColor(res.data.data) }) // } }, 2000) }, changeColor (resultsList) { resultsList.map((item, index) => { // console.log('item', item) if (this.keyWords && this.keyWords.length > 0) { // 匹配关键字正则 let replaceReg = new RegExp(this.keyWords, 'g') // 高亮替换v-html值 let replaceString = '' + this.keyWords + '' resultsList[index].name = item.name.replace( replaceReg, replaceString ) } }) this.results = [] this.results = resultsList } } } .search-text{ color: red; }最后,如果本文对你的学习或者工作有帮助的话,麻烦给个star鼓励下啦~~~ |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |