12 | 小程序实战之搜索页面

12.1 效果

在这里插入图片描述

12.2 页面布局+渲染搜索结果+防抖实现+页面痕迹重置

(1)思路

1 输入框绑定 值改变事件 input事件
1 获取到输入框的值
2 合法性判断
3 检验通过 把输入框的值 发送到后台
4 返回的数据打印到页面上
2 防抖 (防止抖动) 定时器 节流
1 防抖 一般 输入框中 防止重复输入 重复发送请求
2 节流 一般是用在页面下拉和上拉
3 定义全局的定时器id
3 页面痕迹重置
1 取消按钮绑定事件
2 按取消后取消按钮隐藏,搜索框和搜索出来的商品清空

(2)代码
<view class="search_row">
  <input
   value="{{inpValue}}"
   placeholder="请输入您要搜索的商品"
   bindinput="handleInput"
  > </input>
  <button bindtap="handleCancel" hidden="{{!isFocus}}">取消</button>
</view>
<view class="search_content">
  <navigator
   url="/pages/goods_detail/index?goods_id={{item.goods_id}}"
   class="search_item"
   wx:for="{{goods}}"
   wx:key="goods_id"
  >
    {{item.goods_name}}
  </navigator>
</view>
page{
  background-color: #dedede;
  padding: 20rpx;
}
.search_row{
  height: 60rpx;
  display: flex;
  input{
    background-color: #fff;
    flex: 5;
    height: 100%;
    padding-left: 30rpx;
  }
  button{
    flex: 1;
    width: 110rpx;
    height: 100%;
    padding: 0;
    margin: 0 10rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 26rpx;
  }
}
.search_content{
  margin-top: 30rpx;
  .search_item{
    background-color: #fff;
    font-size: 26rpx;
    padding: 15rpx 10rpx;
    border-bottom: 1rpx solid #ccc;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
}
import { request } from "../../request/index.js";
import regeneratorRuntime from '../../lib/runtime/runtime';
Page({
  data: {
    goods:[],
    // 取消 按钮 是否显示
    isFocus:false,
    // 输入框的值
    inpValue:""
  },
  // 定时
  TimeId:-1,
  // 输入框的值改变 就会触发的事件
  handleInput(e){
    // 1 获取输入框的值
    const {value}=e.detail;
    // 2 检测合法性
    if(!value.trim()){
      this.setData({
        goods:[],
        isFocus:false
      })
      // 值不合法
      return;
    }
    // 3 准备发送请求获取数据
    this.setData({
      isFocus:true
    })
    clearTimeout(this.TimeId);
    // 开启定时器
    this.TimeId=setTimeout(() => {
      this.qsearch(value);
    }, 1000);
  },
  // 发送请求获取搜索建议 数据
  async qsearch(query){
    const res=await request({url:"/goods/qsearch",data:{query}});
    console.log(res);
    this.setData({
      goods:res
    })
  },
  // 点击 取消按钮
  handleCancel(){
    this.setData({
      inpValue:"",
      isFocus:false,
      goods:[]
    })
  }
})

在这里插入图片描述

没错,哥哥变懒了 🚑🚑🚑

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值