美文网首页
小程序封装input输入实时搜索

小程序封装input输入实时搜索

作者: Peter_2B | 来源:发表于2020-08-13 13:22 被阅读0次


    <view class="search-row">
        <input placeholder="请输入您要搜索的商品" bindinput="handleInput" value="{{inputValue}}"></input>
        <button hidden="{{!isFocus}}" bindtap="handleCancel">取消</button>
    </view> 
    
    <view class="search-content">
        <navigator class="search-item"  wx:for="{{goods}}" wx:key="goods_id"
               url="/pages/goods_detail/index?goods_id={{item.goods_id}}">
        {{item.goods_name}}
        </navigator>
    </view>
    

    // pages/search/index.js
    import { request } from "../../request/index.js"
    Page({
      data: {
         goods:[],  isFocus:false,  inputValue:'',
      },
      TimeId:1,
      handleInput(e){
      const {value} = e.detail;
      if(!value.trim()){
           this.setData({
                   goods:[],       //清空下方循环出来的所有商品数组
                   isFocus:false   //取消按钮不显示
           })
           return;
       };
       this.setData({ isFocus:true }) //if没有return 否则就执行以下
          clearTimeout(this.TimeId);     //防抖:一般用于输入框     节流:一般上啦,下拉 
          this.TimeId = setTimeout(()=>{   
             this.qsearch(value);
          },1000)
      },
      qsearch(query){
        request({url:"/goods/qsearch",data:{query}}).then(res=>{
            this.setData({  goods: res.data.message  })
        });
      },
      handleCancel(){
        this.setData({
            inputValue:"",  isFocus:false, goods:[]
        })
       },
    })
    

    page{
      background: #dedede;
      padding: 20rpx;
    }
    .search-row{
      height: 80rpx;
      display: flex;
    }
    .search-row input{
      background: #fff;
      flex: 1;
      height: 80rpx;
      padding-left: 30rpx;
    }
    .search-row button{
      width: 110rpx;
      height: 60rpx;
      font-size: 26rpx;
      padding: 0;
      margin: 0 10rpx;
      display: flex;
      justify-content: center;
      align-items: center; 
    }
    
    .search-content{
      margin-top: 30rpx;
      }
    .search-content .search-item{
      background: #fff;
      font-size: 26rpx;
      padding: 15rpx 10rpx;
      border-bottom: 1rpx solid #ccc;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }

    相关文章

      网友评论

          本文标题:小程序封装input输入实时搜索

          本文链接:https://www.haomeiwen.com/subject/aadsrktx.html