<view class="search_row"> <input value="{{inputValue}}" placeholder="请输入你要搜索的商品" bindinput="handleInput"> </input> <button class="search_btn" bindtap="handleCancel" hidden="{{!isFocus}}"> 取消 </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.wxss */ page{ background-color: #dedede; padding: 20rpx; } .search_row{ height: 60rpx; display: flex; input{ background-color: #fff; flex: 1; height: 100%; padding-left: 30rpx; } .search_btn{ width: 110rpx !important; height: 100% !important; line-height: 100% !important; padding: 0 !important; margin: 0 10rpx !important; 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: 1px solid #ccc;
overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } } /** * 页面的初始数据 */ data: { goods:[], // 取消 按钮 是否显示 isFocus: false, inputValue:'' }, TimeId:-1,
// 输入框的值改变 就会触发的事件 handleInput(e){ // console.log(e) // 1 获取输入框的值 const {value} = e.detail; // 检测合法性 if(!value.trim()){
this.setData({ goods:[], isFocus:false })
// 值不合法 return ; }
// 3 准备发送请求 获取数据 this.setData({ isFocus:true })
clearTimeout(this.TimeId); // 4 防抖实现 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({ inputValue:'', isFocus:false, goods:[] }) },