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:[]
})
}
})
没错,哥哥变懒了 🚑🚑🚑