微信小程式實現歷史搜尋記錄的本地儲存和刪除
阿新 • • 發佈:2018-12-31
輸入框和搜尋按鈕表單的wxml,沒啥特別的,這裡綁定了輸入框的輸入值,樣式我就不放上來了
<form class='searchForm' bindsubmit='searchSubmitFn'>
<input value="{{searchValue}}" class='topInput' name='input'/>
<button formType='submit' class='searchBtn'>搜尋</button>
</form>
歷史記錄列表的wxml,也沒啥特別的,就用了個列表迴圈,做了個判斷,當沒有搜尋記錄時顯示沒有搜尋記錄的條目
<view class='historyContent'> <view class='title'> <h>歷史搜尋</h> <image src='../../images/u729.png' class='deleteIcon' bindtap='historyDelFn' ></image> </view> <view class='htrItemContent'> <block wx:for="{{searchRecord}}" wx:key='{{item}}'> <view class='htrItem'>{{item.value}}</view> </block> <view class='noHistoryItem' wx:if="{{searchRecord.length==0}}">你還沒有搜尋記錄</view> </view> </view>
首先設定一下初始值,寫一個取得本地儲存的歷史搜尋記錄列表函式,在頁面onload時候啟用
data: {
inputVal:'',
searchRecord: []
},
openHistorySearch: function () {
this.setData({
searchRecord: wx.getStorageSync('searchRecord') || [],//若無儲存則為空
})
},
頁面onLoad函式裡 載入一下函式就ok了具體的歷史記錄獲取儲存請看下面
onLoad: function (options) { this.openHistorySearch() },
提交表單時的函式 ,這裡是動態改變json陣列的某個健值的話在小程式裡應用整體賦值的方法,強迫症,輸入為空時不把他放到歷史紀錄裡,可以做一些其它跳轉處理,這裡我只顯示最新的五條,不為空且小於五時,直接放到數組裡面,注意我用的是unshift而不是push,因為我想讓最新輸入的在最上面,若已經等於五條則用pop刪掉最老的一條,再放入新的記錄,再存入本地儲存
//點選搜尋按鈕提交表單跳轉並儲存歷史記錄
searchSubmitFn: function (e) {
var that = this
var inputVal = e.detail.value.input
var searchRecord = this.data.searchRecord
if (inputVal == '') {
//輸入為空時的處理
}
else {
//將搜尋值放入歷史記錄中,只能放前五條
if (searchRecord.length < 5) {
searchRecord.unshift(
{
value: inputVal,
id: searchRecord.length
}
)
}
else {
searchRecord.pop()//刪掉舊的時間最早的第一條
searchRecord.unshift(
{
value: inputVal,
id: searchRecord.length
}
)
}
//將歷史記錄陣列整體儲存到快取中
wx.setStorageSync('searchRecord', searchRecord)
}
},
點選垃圾桶刪除歷史紀錄和本地儲存
historyDelFn: function () {
wx.clearStorageSync('searhRecord')
this.setData({
searchRecord: []
})
},