样式如图:
在home.wxml中
1<!-- 2confirm-type:键盘的右下角按钮显示'搜素' 3bindconfirm:按下键盘'搜索'按钮 4bindinput:在输入框输入过程中触发事件 5bindtap:点击搜索图标 6--> 7 8<view class="search"> 9 <input type="text" placeholder="搜索菜品" confirm-type="search" bindconfirm="goSearch" bindinput="getSearch" /> 10 <text bindtap="goSearch" class="icon fa fa-search" /> 11</view>
情况一: ::: tip 搜索后跳转到的页面未在tabBar中定义,可使用 wx.navigateTo 跳转时将 searchKey 带到新页面。 ::: 在home.js中
1let searchKey = ''; 2Page({ 3 // 搜索框数据 4 getSearch(e) { 5 searchKey = e.detail.value 6 }, 7 // 搜索事件 8 goSearch() { 9 if (searchKey && searchKey.length > 0) { 10 wx.navigateTo({ 11 url: '/pages/search/search?searchKey=' + searchKey, 12 }) 13 } else { 14 wx.showToast({ 15 icon: 'none', 16 title: '搜索词为空', 17 }) 18 } 19 } 20})
在search.js中
1const db = wx.cloud.database() 2Page({ 3 onLoad: function (options) { 4 let searchKey = options.searchKey; 5 db.collection('food').where({ 6 name: db.RegExp({ 7 regexp: searchKey, 8 options: 'i' 9 }) 10 }).get() 11 .then(res => { 12 console.log(res) 13 }).catch(res => { 14 console.log(res) 15 }) 16 }, 17})
情况二: ::: tip 搜索后跳转到的页面已在tabBar中定义,使用 wx.navigateTo 会报错 errMsg: “navigateTo:fail can not navigateTo a tabbar page”。
此时可以换成 wx.switchTab 进行跳转,但不能携带参数,所以需要借助全局变量。 ::: 在app.js中
1App({ 2 globalData: { 3 searchKey: '' 4 }, 5})
在home.js中
1let searchKey = ''; 2const app = getApp() 3Page({ 4 // 搜索框数据 5 getSearch(e) { 6 searchKey = e.detail.value 7 }, 8 //点击搜索 9 goSearch() { 10 if (searchKey && searchKey.length > 0) { 11 app.globalData.searchKey = searchKey 12 wx.switchTab({ 13 url: '/pages/food/food', 14 }) 15 } else { 16 wx.showToast({ 17 icon: 'none', 18 title: '搜索词为空', 19 }) 20 } 21 } 22})
在food.js中
1const db = wx.cloud.database() 2const app = getApp() 3Page({ 4 onLoad: function (options) { 5 db.collection('food').where({ 6 name: db.RegExp({ 7 regexp: app.globalData.searchKey, 8 options: 'i' 9 }) 10 }).get() 11 .then(res => { 12 console.log(res) 13 }).catch(res => { 14 console.log(res) 15 }) 16 }, 17})
