微信小程序搜索功能如何实现
在微信小程序功能里面,搜索功能是必不可少的。不管什么样的小程序,对于搜索都是会有一些需要的,接下来跟着小编一起来看看微信小程序搜索功能是如何实现的吧。
因为只是写个搜索页面,所以主页面就没有好好切,见谅。。。主页面就是下面这样:
程序已经托管在github上了:github/Yangzhedi/myBlog-wxapp,大家可以自行下载,之后可以star一下啦~
点击页面中 黄色的input就可以跳转到真正的搜索页面:pages/components/component2/search/search.wxml
搜索页面中也是有个input搜索框,旁边有个小叉号,可以清除input里的文字。
下面主要讲下search页面的逻辑:其实也非常简单。
搜索input绑定bindInput函数,
[javascript] view plain copy print?
bindInput:function(e){
this.setData({
inputValue:e.detail.value
})
console.log('bindInput'+this.data.inputValue)
},
bindInput:function(e){
this.setData({
inputValue:e.detail.value
})
console.log('bindInput'+this.data.inputValue)
},
将输入的值存在inputValue中,搜索button 用bindtap绑定setSearchStorage函数
[javascript] view plain copy print?
setSearchStorage:function(){
let data;
let localStorageValue = [];
if(this.data.inputValue != ''){
//调用API从本地缓存中获取数据
var searchData = wx.getStorageSync('searchData') || []
searchData.push(this.data.inputValue)
wx.setStorageSync('searchData', searchData)
wx.navigateTo({
url: '../result/result'
})
}else{
console.log('空白的你搜个蛋!')
}
// this.onLoad();
},
setSearchStorage:function(){
let data;
let localStorageValue = [];
if(this.data.inputValue != ''){
//调用API从本地缓存中获取数据
var searchData = wx.getStorageSync('searchData') || []
searchData.push(this.data.inputValue)
wx.setStorageSync('searchData', searchData)
wx.navigateTo({
url: '../result/result'
})
}else{
console.log('空白的你搜个蛋!')
}
// this.onLoad();
},
这个函数主要就是先判断输入的值是否不为空,再通过getStorageSync获取到key为searchData的localStorage,
如果第一次还没有set过这个key就获取[],再将用户inputValue存的想要搜索的值放进searchData,之后再跳转到result页面。这里我只放了个案例页面。
如果在真正的生产环境中,这个函数可以通过wx.request向服务器发送请求,再把数据放进result页面中,实现真正的搜索功能。
删除inputValue的button功能实现也很简单,setData将inputValue设置为空字符串就可以了。
放点击result页面左上角的返回时,你就可以发现,你刚才搜索的结果已经放到了search的页面中。
当你想要删除缓存数据的时候,可以点击清空浏览记录按钮,会弹出个对话框:
点击确认删除之后,会自动刷新页面(重定向到本页面),将之前的key为searchData的localStorage重置为空数组。
[javascript] view plain copy print?
modalChangeConfirm:function(){
wx.setStorageSync('searchData',[])
this.setData({
modalHidden:true
})
wx.redirectTo({
url: '../search/search'
})
},
modalChangeConfirm:function(){
wx.setStorageSync('searchData',[])
this.setData({
modalHidden:true
})
wx.redirectTo({
url: '../search/search'
})
},
这里的清除不是应用wx.clearStorage()删除的,以为clearStorage会将所有的localStorage都删掉,慎用!
这样,搜索的功能就做好了!微信小程序搜索功能是怎么实现的,你看一看上述操作就能够明白了,参照这个流程,你也可以试一试。更多相关资料请关注微信小程序素材网。
微信小程序在哪搜索?微信小程序的那些常见问题
微信小程序聊天功能怎么开发和使用
微信小程序分享功能在哪?微信小程序怎么分享?
