商品搜索后端动态获取数据
后端动态获取数据:
/*** 商品搜索* @param q* @return*/@GetMapping("/search")public R search(String q){List<Product> productList = productService.list(new QueryWrapper<Product>().like("name", q));Map<String,Object> map=new HashMap<>();map.put("message",productList);return R.ok(map);}
定义productList
/*** 页面的初始数据*/data: {productList:[], // 商品数组inputValue:"", // 输入框的值isFocus:false // 取消 按钮 是否显示},
前端调用
/*** 请求后端 商品搜索*/async search(q){const result = await requestUtil({url: '/product/search',data:{q}});this.setData({productList: result.productList})},
// 处理input事件handleInput(e){const {value}=e.detail;if(!value.trim()){this.setData({productList:[],isFocus:false})return;}this.setData({isFocus:true})clearTimeout(this.TimeoutId);this.TimeoutId=setTimeout(()=>{this.search(value)},1000)},
页面渲染:
<view class="search_row"><input type="text" model:value="{{inputValue}}" placeholder="请输入商品关键字" bindinput="handleInput"/><button hidden="{{!isFocus}}">取消</button>
</view>
<view class="search_content"><navigatorclass="search_item"wx:for="{{productList}}"wx:key="id"url="/pages/product_detail/index?id={{item.id}}">{{item.name}}</navigator>
</view>
样式:
page{background-color: #F9F9F9;padding-top: 20rpx;
}.search_row{height: 50rpx;display: flex;input{background-color: #FFFFFF;flex:1;height: 100%;padding-left: 30rpx;}button{display:flex;justify-content: center;align-items: center;width:110rpx !important;font-size: 26rpx;padding: 0;margin: 0 10rpx;height: 100%;}
}.search_content{margin-top: 15rpx;padding: 0px;.search_item{background-color: #FFFFFF;font-size: 26rpx;padding: 15rpx;align-items: center;border-bottom: 1rpx solid #EAEAEA;overflow:hidden;white-space: nowrap;text-overflow: ellipsis;}
}
取消按钮:
<view class="search_row"><input type="text" model:value="{{inputValue}}" placeholder="请输入商品关键字" bindinput="handleInput"/><button hidden="{{!isFocus}}">取消</button>
</view>
// 点击 取消按钮handleCancel(){this.setData({productList:[], // 商品数组isFocus:false, // 取消 按钮 是否显示inputValue:"" // 输入框的值})},
搜索性能优化
搞个定时器
// 处理input事件handleInput(e){const {value}=e.detail;if(!value.trim()){this.setData({productList:[],isFocus:false})return;}this.setData({isFocus:true})clearTimeout(this.TimeoutId);this.TimeoutId=setTimeout(()=>{this.search(value)},1000)},