项目实战-点餐小程序-14 首页(搜索菜品)


一、实现思路

  1. 编写搜索框的页面wxml
  2. 美化搜索区域wxss
  3. 获取用户输入的内容
  4. 搜索词为空时候的提示
  5. 正则表达式实现模糊搜索
  6. 手机键盘触发搜索事件
  7. 携带搜索词跳转页面

二、代码实现

1.home.wxml

说明:confirm-type="search" bindconfirm="goSearch" //用来实现手机键盘触发搜索事件
1 <!-- 搜索 -->
2 <view class="searchRoot">
3 <input type="text" class="searchInput" placeholder="搜索菜品" bindinput="getSearchContent" confirm-type="search" bindconfirm="goSearch"></input>
4 <image src="/images/search.png" class="searchIcon" bindtap="goSearch"></image>
5 </view>

2.home.wxss

 1 /*首页 搜索*/
 2 .searchRoot{
 3   display: flex;
 4   flex-direction: row;
 5   /*弹性盒内各项元素沿着主轴居中显示*/
 6   align-items: center;
 7   padding: 20rpx;
 8 }
 9 .searchInput{
10   border: 1rpx solid #FF9966;
11   border-radius: 30rpx;
12   padding: 0 30rpx;
13   flex: 1;
14   height: 76rpx;
15 }
16 .searchIcon{
17   width: 70rpx;
18   height: 70rpx;
19   margin-left: 20rpx;
20 }

2.home.js

  //定义db
  const db = wx.cloud.database()
  //用户输入的搜索关键字
  let searchKey=''
Page({

  //获取用户输入的内容
  getSearchContent(e){
    console.log("用户输入的搜索内容为",e.detail.value);
    searchKey = e.detail.value
  },
  //搜索功能
  goSearch(){
    console.log("用户点击了搜索按钮",searchKey);
    if(searchKey&&searchKey.length>0){
      //携带搜索内容跳转页面
      wx.navigateTo({
        url:"/pages/food/food?searchKey="+searchKey
      })
      //使用正则查询
      db.collection("food").where({ 
        name:db.RegExp({
          regexp:searchKey, //搜索池
          options:'i' //不区分大小写
        })
      }).get()
      .then(res=>{
        console.log("搜索成功",res);
      }).catch(err=>{
        console.log("搜索失败",err);
      })
    }else{
      wx.showToast({
        title: '搜索内容为空',
        icon:"none"
      })
    }
  },

三、效果展示

 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM