当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 微信小程序实现搜索历史功能

微信小程序实现搜索历史功能

2019年07月20日  | 移动技术网IT编程  | 我要评论

结合了微信给的资料,马马虎虎摸索出了一些东西,下面说一下微信小程里序搜索历史功能的实现,下图是实现效果。

首先,定义历史记录的显示风格和方式,在下用的是列表模式,没有使用什么比较酷炫的套路。

<view wx:for="{{sercherstorage}}" wx:key="item.id">
 <view class="liclass" style="color:#9e9e9e;border-bottom:0;font-size:26rpx;" id="{{item.id}}" bindtap="tapsercherstorage">
  <text style="width:100rpx">{{item.name}}</text>
 </view>
</view>

其次是“清除历史记录”按钮,个人建议在没有搜索历史的时候不显示按钮,因为在下有些强迫症

<view wx:if="{{sercherstorage.length!==0}}" style="text-align:center;" bindtap="clearsearchstorage">
 <view class="history-span">清除历史记录</view>
</view>

(微信小程序的数据交互还是蛮喜欢的)

这里是列表的css样式

/*搜索历史列表外部容器样式*/
 .ddclass { 
 position: absolute; 
 width: 100%; 
 margin-top: 10px; 
 left: 0; 

} 


/*搜索历史普通样式*/

 .liclass { 
 font-size: 14px; 
 line-height: 34px; 
 color: #575757; 
 height: 34px; 
 display: block; 
 padding-left: 18px; 
 background-color: #fff; 
 border-bottom: 1px solid #dbdbdb; 
} 

最后是一些js控制

1、参数声明

 data: {
  sercherstorage: [],
  storageflag: false  //显示搜索记录标志位
 }

2、两个主要的js方法

//清除缓存历史
 clearsearchstorage: function () {
  wx.removestoragesync('searchdata')
  this.setdata({
  sercherstorage: [],
  storageflag: false,
  })
 },
 //打开历史记录列表
 openlocationsercher: function () {
  this.setdata({
  sercherstorage: wx.getstoragesync('searchdata') || [], 
  storageflag: true,
  listflag: true,
  })
 }

3、点击搜索添加搜索内容进历史记录

var self = this;
if(self.data.search.length == 0){
 return;
}
//控制搜索历史
var self = this;
if (this.data.search != '') {
 //将搜索记录更新到缓存
 var searchdata = self.data.sercherstorage;
 searchdata.push({
 id: searchdata.length,
 name: self.data.search
 })
 wx.setstoragesync('searchdata', searchdata);
 self.setdata({ storageflag: false, })
}

4、在进入搜索页面时,检索出缓存中的搜索历史。(适用于搜索页面是单独页面的业务)

onload: function (options) {
  this.openlocationsercher();
 }

5、清空历史记录,只需在上面声明搜索按钮时把”bindtap”属性值设置成写好的js方法名即可。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网