搜索框-历史搜索记录
实现功能:
- 历史搜索记录
- 展示-历史搜索记录展示10条
- 点击跳转-点击历史搜索记录可同步到搜索框并自动搜索
- 全部删除-可一次性全部删除历史搜索记录
引言
在微信小程序中,一个带有历史记录的搜索框可以极大地提升用户体验。用户可以快速访问他们之前的搜索,而不必重新输入。本文将详细介绍如何在“我的咖啡店”小程序中实现这一功能。
实现搜索框与历史记录功能
1. 页面初始数据设置
在search.js
中,我们首先定义了页面的初始数据,包括搜索历史列表historyList
和当前搜索关键词keyword
。
// pages/search/search.js
Page({
data: {
historyList: [],
keyword: ""
},
// ...其他函数
});
2. 加载搜索历史
在页面加载时,我们从本地存储中获取搜索历史数组,并更新页面数据。
// pages/search/search.js
onLoad(options) {
let searchKeyArr = wx.getStorageSync('searchKeyArr') || [];
this.setData({ historyList: searchKeyArr });
wx.hideLoading();
},
3. 搜索关键词处理
当用户在搜索框中输入关键词并触发搜索时,我们将关键词添加到搜索历史列表中,并同步到本地存储。
// pages/search/search.js
onSearch() {
let currentKeyword = this.data.keyword.trim();
let hisArr = this.data.historyList || [];
if (currentKeyword && !hisArr.includes(currentKeyword)) {
hisArr.unshift(currentKeyword);
}
hisArr = [...new Set(hisArr)].slice(0, 10);
this.setData({
historyList: hisArr,
keyword: ''
});
wx.setStorageSync('searchKeyArr', hisArr);
},
4. 清空搜索历史
用户可以一次性清空所有搜索历史记录。
// pages/search/search.js
clearHistory() {
this.setData({
historyList: []
});
wx.removeStorageSync('searchKeyArr');