微信小程序历史搜索历史的本地缓存和删除

wxml:

<view class='search_history' wx:if="{{isShow}}">
        <view class='history_title'>最近搜索</view>
        <view class='history_item' wx:for="{{searchRecord}}" wx:key="{{index}}" wx:for-item="hisItem">
          <text bindtap='search_his' data-his="{{hisItem}}">{{hisItem}}</text>
        </view>
        <view class='history_title clear' bindtap='clear_search'>清空搜索历史</view>
</view>

wxss:

.search_history {
  height: auto;
  width: 95%;
  position: relative;
  background-color: #fff;
  border-radius: 5rpx;
  font-size: 30rpx;
  color: #000;
  text-align: left;
}

.history_title {
  color: #999;
  text-align: left;
  padding: 10rpx;
}

.history_item {
  display: inline-block;
  padding: 10rpx 15rpx;
  background-color: rgb(248, 246, 246);
  margin: 10rpx;
  border-radius: 10rpx;
}

.clear {
  display: inline-block;
  padding: 10rpx 15rpx;
  background-color: #66d7fa;
  color: #fff;
  margin: 10rpx;
  border-radius: 10rpx;
}

js:

//js用到的全局变量
Page({
  data: {
    isShow: false,
    searchRecord: [],
  },
//搜索的时候缓存到本地

  searchBox: function(e) {
    let that = this;
    let inputVal = e.detail.value.ip;
    let searchRecord = this.data.searchRecord;
    if (inputVal == "") {
      that.setData({
        ip: inputVal
      })
      return
    } else {
      if (searchRecord.length < 10) {
        searchRecord.unshift(inputVal);
      } else {
        searchRecord.pop();
        searchRecord.unshift(inputVal);
      }
      //将历史记录数组整体储存到缓存中
      wx.setStorageSync('searchRecord', Array.from(new Set(searchRecord)));
    }
    that.setData({
      ip: e.detail.value.ip
    })
  },
  // 缓存历史
  openHistorySearch: function() {
    let that = this;
    that.setData({
      searchRecord: wx.getStorageSync('searchRecord') || [], //若无储存则为空
    })
    console.log(that.data.searchRecord);
  },
  // 清空搜索历史
  clear_search: function() {
    let that = this;
    wx.clearStorageSync('searhRecord')
    that.setData({
      searchRecord: [],
      isShow: false
    })

  },
  // 点击历史搜索
  search_his: function(e) {
    let that = this;
    let his = e.currentTarget.dataset.his;
    that.setData({
      ip: his,
      isShow: false
    });
    that.search_host();
  },

})
  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值