JHJ
JHJ
新手
新手
  • 最后登录2018-03-29
  • 发帖数2
阅读:7394回复:0

微信小程序使用filter、getCurrentPage()实现搜索功能

楼主#
更多 发布于:2017-12-29 12:59
xml页面
<view class='inputBorder'>
    <input placeholder='pw_placeHolder' bindinput='bindKeyInput' confirm-type='search' placeholder-style='font-size:20rpx' ></input>
 </view>
<view wx:for='pw_searchfood' wx:key='index' class='searchlist-content'>
 <view class='searchcontent-img' bindtap='navToDetail' id='pw_index' >
      <image src='pw_item.imageUrls' mode="aspectFill" class='searchImg'></image>
    </view>

js页面
Page({
  data: {
    placeHolder: "请输入",
    buttonSize: 'mini',
    list:[]//将请求出的数据始终保存起来
  },
  //获取输入框的文字
  bindKeyInput: function (e) {
    // console.log(e.detail.value)
    this.search(e.detail.value)
  },
  search: function (key) {
  //  console.log(this);//this指向事件对象,不能获取到this.searchfood
    // console.log(key)
    // this.searchfood
   var cPage = getCurrentPages()[0];//打印cPage 获取其中的data属性
    console.log(cPage)
    var tempfoodlist = cPage.data.list;
    if (!tempfoodlist)
     return;
   var newArr =  tempfoodlist.filter(function (item) {
     //item数组中的每一项 将数组中的每一项获取保存起来
      return item.title.indexOf(key)>-1;
    })
   console.log(newArr);//对应搜索的一条数据
   cPage.setData({
     searchfood:newArr
   })
  },
  onLoad: function (options) {
    var that = this;
    wx.request({
      url: '输入请求地址',
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        // console.log(res.data.data)
        var foodList = res.data.data;
        that.setData({
          searchfood: foodList,
          list:res.data.data
        })
      }
    }
  },
})

建议大家多看看es6数组方法

最新喜欢:

doubleyongdouble...
游客


返回顶部

公众号

公众号