利用微信小程序weui库的SearchBar组件实现简易搜索功能

  • Post author:
  • Post category:小程序


鉴于搜索对象的数据类型简单,简单list就可以处理,故直接存在下面的hosList里面;当然一般还是应该单拿出个文件来存数据;

先上index.js代码:

var value = '';
var hosList=[];
Page({
  data: {
      inputShowed: false,
      inputVal: "",

    },
   
  onLoad() {
      this.setData({
          search: this.search.bind(this),
      })   
  },
  search: function (value) {
    var fitList = [];
    var result = new Object();
    result.text = '';
    result.value = 0;
    var resultList=[];
    hosList= [
    //此处放置搜索结果的列表数据
    '当时明月在,曾照彩云归',
    '去年春恨却来时。落花人独立,微雨燕双飞。'
      ]
      var indexList=[];
      return new Promise((resolve, reject) => {
          for (var i of hosList){
            if(i.search(value)!= -1){
              fitList.push(i);//将匹配到的搜索结果推到fitList里
            }
          }
          
          //调整搜索结果列表fitList的格式
          //类似于 [{text: '搜索结果', value: 1}, {text: '搜索结果2', value: 2}]
            //}, 200)
          for (i of fitList){
            result.text = i;
            resultList.push(result);
            result = {};
          }
      console.log(resultList);//返回搜索结果
          resolve(resultList);
      })
  },
  selectResult: function (e) {
      console.log('select result', e.detail)
  },
});

json

{
  "usingComponents": {"mp-searchbar": "weui-miniprogram/searchbar/searchbar"},
  "navigationBarTitleText": "搜索页面"
}

wxml

<view class="page">
    <view class="page__hd">
        <view class="page__title">SearchBar</view>
        <view class="page__desc">搜索栏</view>
    </view>
    <view class="page__bd">
        <mp-searchbar bindselectresult="selectResult" search="{{search}}"></mp-searchbar>
    </view>
</view>

wxss

page {
  background-color: #dedede;
  padding: 20rpx;
  width: auto;//这里最好调一下,不然组件可能会偏
}

请参考

SearchBar组件官网文档



版权声明:本文为today__present原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。