一、實現思路
- 編寫搜索框的頁面wxml
- 美化搜索區域wxss
- 獲取用戶輸入的內容
- 搜索詞為空時候的提示
- 正則表達式實現模糊搜索
- 手機鍵盤觸發搜索事件
- 攜帶搜索詞跳轉頁面
二、代碼實現
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" }) } },
三、效果展示