微信小程序联想搜索
首先在视图层写一个搜索框
<input type="text" placeholder="请输入要搜索的商品名称" bindinput="search"/></view>
// 循环输出结果
<block wx:for="{{search}}">
<view>{{item}}</view>
</block>
在js中方法
search(e){
// 清除之前的定时器
clearTimeout(this.data.timer)
// 启动新的定时器
this.data.timer = setTimeout(()=>{
// 取出搜索的值
let search = e.detail.value
// 取出数据源
let searchInfo=this.data.searchInfo
// 判断搜索值是否为空
if(search==""){
// 为空返回一个空数组
return this.setData({search:[]})
}
// 创建正则对象
let reg =new RegExp(search);
// 定义一个容器接收数据源
let res =[]
// 循环
res=searchInfo.filter((item,key)=>{
// 返回通过正则的数据
return reg.test(item)
})
// 将结果刷新至视图层
this.setData({search:res})
},800)
},

浙公网安备 33010602011771号