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

2019-11-12,,

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

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

<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方法名即可。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持北冥有鱼。

您可能感兴趣的文章:

  • 微信小程序下拉框搜索功能的实现方法
  • 微信小程序实现搜索功能并跳转搜索结果页面
  • 微信小程序首页的分类功能和搜索功能的实现思路及代码详解
  • 微信小程序实现全局搜索代码高亮的示例
  • 微信小程序搜索组件wxSearch实例详解
  • 微信小程序 组件的外部样式externalClasses使用详解
  • 微信小程序 搜索框组件代码实例

《微信小程序实现搜索历史功能.doc》

下载本文的Word格式文档,以方便收藏与打印。