主要思路:在云函数获取所有字段,根据客户端传来的value值来搜索筛选相应的字段,再去返回给客户端,客户端拿到返回的数据,在输入搜索内容时,调用该云函数,返回相应的字段,渲染到提示列表,实现搜索功能
1.云函数部分
'use strict';
const db = uniCloud.database()
const $ = db.command.aggregate
exports.main = async (event, context) => {
// 接收分类
const {
user_id,
value
} =event
const userinfo = await db.collection('user').doc(user_id).get()
const article_likes_ids = userinfo.data[0].article_likes_ids
// var name =event.name
// 聚合,更精细化, 求和,分组,指定哪些字段
const list = await db.collection("article")
.aggregate()
.addFields({
is_like:$.in(['$_id',article_likes_ids])
})
.project({
content:0
})
.match({
// RegExp 正则
title:new RegExp(value)
})
.end()
return{
code :200,
msg:"数据请求成功",
data:list.data
}
};
2.云函数调用
<template>
<view class="home">
<navbar :isSearch="true" @input="change"></navbar>
<view class="home-list">
<view v-if="is_history" class="label-box">
<view class="label-header">
<text class="label-title">搜索历史</text>
<text class="label-clear">清空</text>
</view>
<view v-if="historyLists.length>0" class="label-content">
<view class="label-content_item" v-for="item in historyLists ">{{item.name}}</view>
</view>
<view v-else class="no-data">
没有搜索历史
</view>
</view>
<list-scroll v-else class="list-scroll" @loadmore="loadmore">
<list-card v-for="(item) in searchList" :key="item.id" :item="item" mode="item.mode"></list-card>
</list-scroll>
</view>
</view>
</template>
<script>
import {
mapState
} from "vuex"
export default {
data() {
return {
is_history: true,
searchList:[]
}
},
computed: {
...mapState(["historyLists"])
},
onLoad(){
// this.getSearch(value)
},
methods: {
//value是子组件传过来的输入框内容 搜索组件传过来的事件,根据自己的实际情况去写
change(value) {
if(!value){
clearTimeout(this.timer)
this.mork = false
this.getSearch(value)
return
}
//节流的作用,限制请求次数
if(!this.mark){
this.mork=true
//让搜索功能一秒执行一次,否则输入一个字母,函数就会执行一次
this.timer = setTimeout(()=>{
this.mork = false
this.getSearch(value)
},1000)
}
},
//这里是调用云函数
getSearch(value){
if(!value){
this.searchList=[]
this.is_history =true
return
}
this.is_history=false
this.$api.get_search({
value
}).then(res=>{
const {data} =res
console.log(data)
this.searchList=data
})
},
}
}
</script>