在首页单击搜索框跳转到搜索页面

在搜索页面输入搜索关键字,显示出匹配的结果

首先添加搜索页面,在app.json中的pages配置项添加pages/search/search,创建搜索页

使用WeUI组件库提供的搜索框组件实现搜索页面,代码如下

搜索页面代码:

  1. <view class="weui-search-bar">
  2. <view class="weui-search-bar__form">
  3. <view class="weui-search-bar__box">
  4. <icon class="weui-icon-search_in-box" type="search" size="14"></icon>
  5. <input type="text" class="weui-search-bar__input"
  6. value="{{searchWords}}" focus="{{searchInputFocus}}"
  7. bindInput="onSearchInputType" />
  8. <!--清空内容的icon-->
  9. <view class="weui-icon-clear" wx:if="{{searchWords.length > 0}}"
  10. bindTap="clearSearchInput">
  11. <icon type="clear" size="14"></icon>
  12. </view>
  13. </view>
  14. <!-- 单击取消后搜索框显示的文字 -->
  15. <label class="weui-search-bar__label" hidden="{{searchInputFocus}}"
  16. bindTap="showSearchInput">
  17. <icon class="weui-icon-search" type="search" size="14"></icon>
  18. <view class="weui-search-bar__text">搜索</view>
  19. </label>
  20. </view>
  21. <view class="weui-search-bar__cancel-btn" hidden="{{!searchInputFocus}}"
  22. bindTap="onTapSearchBtn">
  23. <block wx:if="{{searchWords.length == 0}}">取消</block>
  24. <block wx:else>搜索</block>
  25. </view>
  26. </view>
  27. <!--即时搜索词列表-->
  28. <view class="weui-cells searchbar-result" wx:if="{{wordsList.length > 0}}">
  29. <navigator url="/pages/item/item?id={{item.id}}"
  30. wx:for="{{wordsList}}" wx:key="{{item.id}}"
  31. class="weui-cell">
  32. <view class="weui-cell__bd">
  33. <view>{{item.title}}</view>
  34. </view>
  35. </navigator>
  36. </view>

input组件用于绑定事件

当用户输入时
获取用户输入的内容
从数据库请求search集合
展示实时搜索结果

如图5.21所示。
image.png

search.js

  1. Page({
  2. data: {
  3. searchInputFocus: true,
  4. searchWords: "",
  5. wordsList: [],
  6. movies: []
  7. },
  8. onTapSearchBtn() {
  9. this.setData({
  10. searchInputFocus: false,
  11. searchWords: "",
  12. wordsList: []
  13. });
  14. },
  15. showSearchInput() {
  16. this.setData({
  17. searchInputFocus: true
  18. });
  19. },
  20. // 清空输入框中的内容
  21. clearSearchInput() {
  22. this.setData({
  23. searchWords: ""
  24. });
  25. },
  26. // 在搜索框中输入内容
  27. onSearchInputType(e) {
  28. var that = this;
  29. let words = e.detail.value
  30. this.setData({
  31. searchWords: words
  32. });
  33. var db = wx.cloud.database();
  34. db.collection("search")
  35. .get()
  36. .then(res => {
  37. console.log(res)
  38. if (res.data[0].subjects.length) {
  39. that.setData({
  40. wordsList: res.data[0].subjects
  41. });
  42. }
  43. })
  44. }
  45. })