uniapp云函数实现搜索功能

这篇博客详细介绍了如何使用云函数配合客户端实现搜索功能。首先,云函数通过获取所有字段并根据客户端传来的value值进行筛选,然后返回相应数据。在前端,当用户输入搜索内容时,调用云函数并渲染搜索结果。文章还展示了具体的云函数代码和前端模板,包括Vue组件的使用,以及如何处理搜索历史和实时搜索建议。
摘要由CSDN通过智能技术生成

主要思路:在云函数获取所有字段,根据客户端传来的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>
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值