- Published on
小程序-用户搜索历史
- Authors
- Name
- zoe
今天在写商品搜索时,要记录用户的搜索历史。用 setStorage 建立一个数组,每次进入商品搜索页面,加载。 代码如下: 一:一进去先读取 history 表
onLoad:function(){
const that=this;
wx.getStorage({
key: 'history',
success: function(res) {
that.setData({
recent_key:res.data
});
}
});
}
二:用户输入完毕,点击搜索时触发这个事件 getGoodsList
<view class="search-input">
<icon class="search-icon" type="search" size="16"></icon>
<input type="text" placeholder="搜索商品名称" confirm-type='search' value="{{inputValue}}" bindconfirm="getGoodsList" />
</view>
三:在这个事件里存储用户输入的商品名,其实还有发起搜索请求的作用,这里不放了
get_history:function(){
const that=this;
wx.getStorage({
key: 'history',
success: function(res) {
that.setData({
recent_key:res.data
});
}
});
},
getGoodsList:function(e){
//建立历史记录表
this.setData({
inputValue:e.detail.value
})
const inputValue=this.data.inputValue;
let history=this.data.recent_key;
history.push(inputValue)
wx.setStorage({
key:'history',
data:history
})
this.get_history();//把storage的数据存到data里
}
四,删除 history 表
<image src="/images/icon/icon-delete.png" bindtap="delete_recent"></image>
delete_recent:function(){
const that=this;
wx.removeStorage({
key: 'history',
success (res) {
that.setData({
recent_key:[]
})
}
})
},