項目實戰-點餐小程序-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