小程序做云开发的模糊搜索可以使用api: dbCmd.or({title: new RegExp(event.title, 'i')}),根据关键词搜索,模糊匹配返回相关数组,下面是具体的云函数
'use strict';
exports.main = async (event, context) => {
//event为客户端上传的参数
console.log('event : ', event)
return new Promise((resolve, reject) => {
const db = uniCloud.database();
const dbCmd = db.command
// 模糊搜索
db.collection('articles')
.where(dbCmd.or({
title: new RegExp(event.title, 'i')
})).get()
.then((res) => {
console.log(res)
resolve(res)
}).catch((err) => {
reject(res)
})
})
//返回数据给客户端
return event
};
页面调用的代码
searchInput(e) {
uniCloud.callFunction({
name: "search",
data: {
"title": e,
}
}).then(res = >{
//如果匹配到的结果>1,证明是拿到结果,就可以将数据返回给界面
if (res.result.affectedDocs > 0) {
console.log(res) this.info = this.changeColor(res.result.data, e) this.isShow = true this.isShowIpt = false
} else {
this.info = [] //恢复初始状态
this.isShow = false //关闭显示区域
this.isShowIpt = false
}
})
},
在watch做防抖节流避免多次触发调用接口
watch: {
ipt(curVal, oldVal) {
clearTimeout(this.timeId) this.timeId = setTimeout(() = >{
if (this.ipt != '') {
this.searchInput(curVal)
} else {
this.info = [],
this.isShowIpt = true
}
},
1000)
}
},
关键词高亮,正则表达式匹配替换,view使用v-html渲染
changeColor(arr, keyword) {
arr.map((item, index) = >{
if (keyword) {
let reg = new RegExp(keyword, 'ig')
let str = ` < span style = "color: #007AFF" > $ {keyword} < /span>`
arr[index].title2 = item.title.replace(reg, str)
}
})
return arr
},