微信小程序联想搜索

首先在视图层写一个搜索框

<input type="text" placeholder="请输入要搜索的商品名称" bindinput="search"/></view>
// 循环输出结果
<block wx:for="{{search}}">
<view>{{item}}</view>
</block>

在js中方法

  search(e){
    // 清除之前的定时器
    clearTimeout(this.data.timer)
    // 启动新的定时器
    this.data.timer = setTimeout(()=>{
      // 取出搜索的值
      let search = e.detail.value
      // 取出数据源
      let searchInfo=this.data.searchInfo
      // 判断搜索值是否为空
      if(search==""){
        // 为空返回一个空数组
        return this.setData({search:[]})
      }
      // 创建正则对象
      let reg =new RegExp(search);
      // 定义一个容器接收数据源
      let res =[]
      // 循环
      res=searchInfo.filter((item,key)=>{
        // 返回通过正则的数据
        return reg.test(item)
      })
      // 将结果刷新至视图层
      this.setData({search:res})
      },800)
  },

posted @   哎呀呀哈  阅读(78)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示