700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > 微信小程序 实现搜索功能

微信小程序 实现搜索功能

时间:2022-06-19 10:08:58

相关推荐

微信小程序 实现搜索功能

阅读说明

采用了组件的技术点来整理代码使用到了数据库操作使用到了 input 标签书写了 loading 加载中等操作涉及到了组件的传值仅供参考
search 页面 书写请求界面

<view><view class="select"><input type="text" placeholder="{{subtitle}}" value="{{search}}" bindchange="handlerSearch" /></view><!--用于展示 搜索到的信息的组件--><view class="list"><product wx:for="{{list}}" wx:key="id" item="{{item}}" /></view></view>

采用 js 里面的数据,动态的数据,效果是能够设置 value 显示的值(更好的体验)bindchange作用是失去光标以后执行操作collectionName是传递过去的值

search 页面 书写 js 代码
书写初始数据

data: {search:null, // value 的值subtitle:"请输入查询内容...", //提示内容list:[], },

书写事件函数 进行请求(代码是连续的,只是为了更好地介绍就分开了)

handlerSearch(e){if(!e.detail.value.trim()){//查看内容是否为空this.setData({list:[],search:null,})return; //阻止后续代码}

this.setData({list:[],//每次搜索内容的时候,需要清空,(因为如果不清空的话可能会数据叠加)search:e.detail.value //e.detail.value input 传来的数据})this.loadList() //执行下一步},

//加载数据async loadList(){let res = await ceshi({//调用请求数据的接口collectionName:"collect", //请求的集合的名字data:{search:this.data.search //查询的条件}})this.setData({list:res.data //请求成功返回的参数})},

附件(查询代码)

let db = wx.cloud.database()export default ({collectionName,data})=>{return new Promise((resolve,reject)=>{let where = {}let title = {$regex:'.*'+data.search, //包含data.search就可以$options:"i" //忽略大小写匹配}where = data.search ? {...where,title} : where //根据data.search关键字查询,如果包含此关键字,则返回对应数据selectData(){db.collection(collectionName).where(where).get({success(res){resolve(res)},fail(err){reject(err)},}) },}

展示内容的组件

//注册组件 在 app.json 里面"usingComponents": {"product": "/components/product/product",},

//接收参数 本页面 js 文件中properties: {item:{//接受外部传入的item属性type:Object},},

<view class="item"><block wx:for="{{item.directors}}" wx:key="id">{{item.name}} </block> <!--循环遍历数据--></view>

end

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。