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(); },})小程序













