微信小程序历史搜索记录加载
关于搜索历史记录保存在哪的讨论
大部分微信小程序不管是购物类的还是知识分享类, 都会有模糊查询功能, 然而有搜索, 就会有搜索记录, 搜索记录也会提升用户的体验感,用户搜索记录也是放埋点最佳的地方
搜索记录的最基本需求如下:
- 最新搜索的排在最前
- 一般是保留最新搜索的n条(下面以保留10条为例)
- 能一键清空
虽然也不太清楚大厂的搜索记录是保存在前端还是后端传过来的我最近做的这个项目的搜索记录,是直接存在了本地(localStorage),历史记录也简单的就是用字符串数组来的. 原因包括:
- 后端回统计关键词搜索量等(埋点), 但是不会记录每个人的搜索历史(没设计搜索历史的表)
- 搜索记录存储量不大, 一般就是最近搜索的10条, 不会占用很大存储空间
- 搜索记录如果因换手机等因素消失也无妨等等
页面效果如下:
相关代码
废话不多说了, 上代码:
.wxml 文件中 一个搜索input+历史记录按钮组"
<input type="text" auto-focus confirm-type="search" bindconfirm="getInputValue" value="{{inputValue}}"/>
<block wx:if="{{ history && history.length!=0 }}">
<view class="hotbox">
<view class="text">搜索历史:</view>
<view wx:for="{{ history }}" wx:key="*this">
<navigator url="/pages/...?inputValue={{ item }}" class="label">{{item}}</navigator>
</view>
</view>
<view class="clear" bindtap="clearHis">清除搜索历史</view>
</block>
.js 文件中
const app = getApp()
Page({
data: {
//历史记录数组
history: [],
//搜索输入框
inputValue: null
},
/** * 生命周期函数--监听页面显示 */
onShow: function () {
let history = wx.getStorageSync('history');
if (history) {
//如果有搜索历史的本地
this.setData({
history: history
})
} else {
//没有搜索历史时
wx.setStorageSync('history', []);
}
},
methods: {
getInputValue: function (e) {
//开始处理历史记录(其实这里可以再封装成一个方法,这里为了把思路缕清)
console.log("搜索关键词:"+e.detail.value.trim());
//排除一下输入为空的情况
if(!e.detail.value||e.detail.value.trim()==""){
wx.navigateTo({
url: '/pages/...',
})
}else{
let oldhistory=wx.getStorageSync('history');
//搜索历史去重
let history = oldhistory.filter(item => {
return item !== e.detail.value.trim()
})
//限制长度为10
if(history.length>9){
history.pop();
}
//添加新历史
history.unshift(e.detail.value.trim());
//存入localStorage
wx.setStorageSync('history',history);
//跳转页面 (毕竟是要跳转到搜索列表页面的)
wx.navigateTo({
url: '/pages/...' + e.detail.value.trim(),
})
}
},
//清除历史记录
clearHis: function (e) {
wx.setStorageSync('history', []);
this.setData({
history: []
})
}
}
})
所以无非就是对数组的操作, 只是好好梳理一下逻辑
这是在CSDN上的第一篇文章, 欢迎切磋
以上内容纯属原创,如需引用,请附上链接,感谢