「小程序 — 云开发」搜索跳转

文章封面

样式如图: image 在home.wxml中

<!-- 
confirm-type:键盘的右下角按钮显示'搜素'
bindconfirm:按下键盘'搜索'按钮
bindinput:在输入框输入过程中触发事件
bindtap:点击搜索图标
-->

<view class="search">
  <input type="text" placeholder="搜索菜品" confirm-type="search" bindconfirm="goSearch" bindinput="getSearch" />
  <text bindtap="goSearch" class="icon fa fa-search" />
</view>

情况一: ::: tip 搜索后跳转到的页面未在tabBar中定义,可使用 wx.navigateTo 跳转时将 searchKey 带到新页面。 ::: 在home.js中

let searchKey = '';
Page({
  // 搜索框数据
  getSearch(e) {
    searchKey = e.detail.value
  },
  // 搜索事件
  goSearch() {
    if (searchKey && searchKey.length > 0) {
      wx.navigateTo({
        url: '/pages/search/search?searchKey=' + searchKey,
      })
    } else {
      wx.showToast({
        icon: 'none',
        title: '搜索词为空',
      })
    }
  }
})

在search.js中

const db = wx.cloud.database()
Page({
  onLoad: function (options) {
    let searchKey = options.searchKey;
    db.collection('food').where({
        name: db.RegExp({
          regexp: searchKey,
          options: 'i'
        })
      }).get()
      .then(res => {
        console.log(res)
      }).catch(res => {
        console.log(res)
      })
  },
})

情况二: ::: tip 搜索后跳转到的页面已在tabBar中定义,使用 wx.navigateTo 会报错 errMsg: “navigateTo:fail can not navigateTo a tabbar page”。

此时可以换成 wx.switchTab 进行跳转,但不能携带参数,所以需要借助全局变量。 ::: 在app.js中

App({
  globalData: {
    searchKey: ''
  },
})

在home.js中

let searchKey = '';
const app = getApp()
Page({
  // 搜索框数据
  getSearch(e) {
    searchKey = e.detail.value
  },
  //点击搜索
  goSearch() {
    if (searchKey && searchKey.length > 0) {
      app.globalData.searchKey = searchKey
      wx.switchTab({
        url: '/pages/food/food',
      })
    } else {
      wx.showToast({
        icon: 'none',
        title: '搜索词为空',
      })
    }
  }
})

在food.js中

const db = wx.cloud.database()
const app = getApp()
Page({
  onLoad: function (options) {
    db.collection('food').where({
        name: db.RegExp({
          regexp: app.globalData.searchKey,
          options: 'i'
        })
      }).get()
      .then(res => {
        console.log(res)
      }).catch(res => {
        console.log(res)
      })
  },
})

评论

暂无评论