微信小程序云开发模糊搜索功能的实现

这是效果图:微信小程序云开发模糊搜索功能的实现_第1张图片微信小程序云开发模糊搜索功能的实现_第2张图片
话不多说,上代码,js、wxml采用的是weui里的模板
js:


Page({

  /**
   * 页面的初始数据
   */
  data: {
    inputVal: '',
    inputShowed: false,
    search_list1: [],
  },
  showInput: function () {
    this.setData({
      inputShowed: true
    });
  },
  hideInput: function () {
    this.setData({
      inputVal: "",
      inputShowed: false
    });
  },
  clearInput: function () {
    this.setData({
      inputVal: ""
    });
  },
  inputTyping: function (e) {
    this.setData({
      inputVal: e.detail.value
    });
    //连接数据库
    const db = wx.cloud.database()
    var that = this
    db.collection('book').where({
      //使用正则查询,实现对搜索的模糊查询
      name: db.RegExp({
        regexp: e.detail.value,
        //从搜索栏中获取的value作为规则进行匹配。
        options: 'i',
        //大小写不区分
      }),
      
    }).limit(10).get({
      success: res => {
        console.log(res)
        that.setData({
          search_list1: res.data
        })
      }
    })
  }
  })

wxml:

<view class="page">
  <view class="page__bd">
    <view class="weui-search-bar">
      <view class="weui-search-bar__form">
        <view class="weui-search-bar__box">
          <icon class="weui-icon-search_in-box" type="search" size="14"></icon>
          <input type="text" class="weui-search-bar__input" placeholder="搜索" value="{{inputVal}}" focus="{{inputShowed}}" bindinput="inputTyping" />
          <view class="weui-icon-clear" wx:if="{{inputVal.length > 0}}" bindtap="clearInput">
            <icon type="clear" size="14"></icon>
          </view>
        </view>
        <label class="weui-search-bar__label" hidden="{{inputShowed}}" bindtap="showInput">
          <icon class="weui-icon-search" type="search" size="14"></icon>
          <view class="weui-search-bar__text">搜索</view>
        </label>
      </view>
      <view class="weui-search-bar__cancel-btn" hidden="{{!inputShowed}}" bindtap="hideInput">取消</view>
    </view>
    <view class="weui-cells searchbar-result" wx:if="{{inputVal.length > 0}}" wx:for="{{search_list1}}">
      <navigator url="./book?whatbook={{item.sx}}" class="weui-cell" hover-class="weui-cell_active">
        <view class="weui-cell__bd">
          <view>书本名:{{item.name}}</view>
        </view>
      </navigator>
    </view>
  </view>
</view>

你可能感兴趣的:(云开发)