以上为搜索界面
小程序wxml页面
。
<input type="text" class="weui-search-bar__input" bindinput="input_key" bindconfirm="Load" value="{{input_key}}" />
<view class="weui-icon-clear" wx:if="{{input_key.length > 0}}" bindtap="clearInput">
<icon type="clear" size="12"></icon>
</view>
<view class="weui-search-bar__cancel-btn" bindtap="Load" data-type="1">搜索</view>
<view style="display: flex;align-items: center; margin-top:5px;">
<text class="titleHot">历史记录</text>
<icon class="clearHistory" type="clear" size="12" bindtap="remove"></icon>
</view>
<view class="listHotCi">
<view wx:for="{{history}}" class="hotCiText" data-id="{{item.name}}" wx:key="item" bindtap="historyJiLu">
<text >{{item.name}}</text>
</view>
</view>
小程序js页面
。
历史记录是先把获取到的数据,加入缓存,再取到缓存中的数据,加到wxml需要用到的数组里,再判断数组中是否已存在时,最开始使用indexOf,但是返回值一直都是-1,解决方法和疑问在下一个文档里
。
Page({
data: {
input_key: '',
history:[],
splist: []
},
Load: function (tag) {
var that = this;
if (this.data.input_key == "" ){
}
else if (this.data.input_key !== "") {
//历史记录写入缓存和获取
var array = that.data.history;
if (array.length < 8 && array.length > 0) {
// 判断数组中是否已存在
var newArr = array.findIndex(function (item) {
return item.name === that.data.input_key;
});
console.log(newArr);
if (newArr != -1) {
// 删除已存在后重新插入至数组
array.splice(newArr, 1)
array.unshift({ name: that.data.input_key })
} else {
array.unshift({ name: that.data.input_key })
}
} else if (array.length =0){
array.unshift({ name: that.data.input_key })
}
else {
array.pop()//删掉旧的时间最早的第一条
array.unshift({ name: that.data.input_key })
}
wx.setStorageSync('lishi', array);
that.getHistory();
}
},
//清除文本框的value
clearInput:function(){
var that = this;
that.setData({
input_key : ""
})
},
//历史记录获取缓存
getHistory:function(){
var that=this;
wx.getStorage({
key: "lishi",
success: function (res) {
that.setData({
history: res.data
})
}
})
},
//清除历史记录
remove:function(e){
var that = this;
wx.removeStorageSync('lishi')
that.setData({
history: [],
})
},
//点击历史记录中的标签,搜索
historyJiLu:function(e){
var that = this;
that.setData({
input_key: e.currentTarget.dataset.id
})
this.Load();
},
onLoad: function (options) {
this.getHistory();
},
})