第十八章 搜索历史保存功能实现记录

第十八章 搜索历史保存功能实现记录 功能目标为微信小程序我的统计页面index增加搜索历史保存功能记录用户搜索过的关键词提升重复搜索效率。核心特性✅ 自动保存搜索关键词最多10条✅ 展示搜索历史列表✅ 点击历史记录快速搜索✅ 支持删除单条历史✅ 支持清空全部历史✅ 使用微信小程序 Storage 本地存储️ 技术方案整体架构用户执行搜索 ↓ 搜索成功 ↓ 保存到本地存储 (wx.setStorageSync) ↓ 更新历史记录列表 ↓ 展示在搜索框下方 用户点击历史记录 ↓ 触发搜索 ↓ 展示搜索结果技术选型层级技术说明数据存储微信小程序 Storage本地持久化性能优异数据结构Array简单数组最多10条去重算法filter unshift移除旧的添加新的到头部UI 展示Flex 布局标签式展示响应式换行交互反馈Toast Modal删除提示、清空确认 实现过程第一阶段数据结构调整1. 新增数据字段文件:index.jsdata:{// ... 原有字段// 搜索历史相关字段searchHistory:[]// 搜索历史列表}关键点:初始值为空数组页面加载时从 Storage 读取每次增删改后更新第二阶段核心方法实现2. saveSearchHistory 方法保存历史文件:index.js/** * 保存搜索关键词到历史记录 * param {string} keyword - 搜索关键词 */saveSearchHistory(keyword){if(!keyword||!keyword.trim()){return;}consttrimmedKeywordkeyword.trim();// 读取现有历史lethistorywx.getStorageSync(vote_search_history)||[];// 去重移除已存在的相同关键词historyhistory.filter(itemitem!trimmedKeyword);// 添加到最前面history.unshift(trimmedKeyword);// 限制最多10条if(history.length10){historyhistory.slice(0,10);}// 保存到本地存储wx.setStorageSync(vote_search_history,history);// 更新页面数据this.setData({searchHistory:history});}技术要点:空值检查: 空关键词不保存去重逻辑: 先 filter 移除旧的再 unshift 添加新的数量限制: 超过10条用 slice 截断同步存储: 使用 setStorageSync避免异步复杂性UI 更新: 立即 setData 刷新界面调用时机: 在performSearch成功后调用3. loadSearchHistory 方法加载历史文件:index.js/** * 从本地存储加载搜索历史 */loadSearchHistory(){consthistorywx.getStorageSync(vote_search_history)||[];this.setData({searchHistory:history});}调用时机: 页面onShow时调用优点:每次进入页面都加载最新数据首次使用返回空数组不会报错4. deleteHistoryItem 方法删除单条文件:index.js/** * 删除单条搜索历史 * param {object} e - 事件对象 */onDeleteHistoryItem(e){constindexe.currentTarget.dataset.index;consthistory[...this.data.searchHistory];history.splice(index,1);// 更新存储wx.setStorageSync(vote_search_history,history);// 更新页面this.setData({searchHistory:history});wx.showToast({title:已删除,icon:success,duration:1000});}交互设计:不需要二次确认用户体验更好立即更新 UI 和存储Toast 提示友好5. clearAllHistory 方法清空全部文件:index.js/** * 清空所有搜索历史 */clearAllHistory(){wx.showModal({title:确认清空,content:确定要清空所有搜索历史吗,success:(res){if(res.confirm){wx.removeStorageSync(vote_search_history);this.setData({searchHistory:[]});wx.showToast({title:已清空,icon:success});}}});}交互设计:二次确认防止误操作使用 removeStorageSync 彻底清除清空后隐藏历史记录区域6. onHistoryItemClick 方法点击搜索文件:index.js/** * 点击历史记录触发搜索 * param {object} e - 事件对象 */onHistoryItemClick(e){constkeyworde.currentTarget.dataset.keyword;// 设置搜索框内容this.setData({searchKeyword:keyword});// 执行搜索this.performSearch(keyword);}流程:获取点击的关键词填充搜索框触发搜索自动更新历史顺序saveSearchHistory 会处理第三阶段集成到现有流程7. 修改 performSearch 方法文件:index.js在搜索成功后调用saveSearchHistory:performSearch(keyword){// ... 原有代码success:res{if(res.datares.data.code200){// ... 原有代码// 保存搜索历史this.saveSearchHistory(keyword);}}}目的: 确保只有搜索成功才保存历史8. 修改 onShow 方法文件:index.jsonShow(){this.loadSearchHistory();// 加载搜索历史this.loadFirstPage();// ... 原有代码}目的: 每次进入页面都加载最新历史第四阶段UI 实现9. WXML 结构文件:index.wxml在搜索框下方增加历史记录区域!-- 搜索历史 --viewwx:if{{searchHistory.length 0}}classsearch-historyviewclasshistory-headertextclasshistory-title搜索历史/texttextclasshistory-clearbindtapclearAllHistory清空历史/text/viewviewclasshistory-listviewclasshistory-itemwx:for{{searchHistory}}wx:key*thisbindtaponHistoryItemClickdata-keyword{{item}}textclasshistory-text{{item}}/textviewclasshistory-deletecatchtaponDeleteHistoryItemdata-index{{index}}text✕/text/view/view/view/view设计亮点:条件渲染: 只在有历史时显示wx:if列表循环:wx:for遍历历史数组事件绑定:外层bindtap触发搜索内层catchtap阻止冒泡删除单条数据传递:data-keyword传递关键词data-index传递索引10. WXSS 样式文件:index.wxss/* 搜索历史 */.search-history{padding:20rpx 30rpx;background:#fff;border-bottom:1rpx solid #f0f0f0;}.history-header{display:flex;justify-content:space-between;align-items:center;margin-bottom:16rpx;}.history-title{font-size:26rpx;color:#999;}.history-clear{font-size:24rpx;color:#ff4d4f;}.history-list{display:flex;flex-wrap:wrap;gap:16rpx;}.history-item{display:flex;align-items:center;padding:12rpx 20rpx;background:#f5f5f5;border-radius:32rpx;max-width:100%;}.history-text{font-size:26rpx;color:#333;flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}.history-delete{width:32rpx;height:32rpx;display:flex;align-items:center;justify-content:center;margin-left:8rpx;color:#999;font-size:20rpx;}.history-delete:active{background:rgba(0,0,0,0.1);border-radius:50%;}设计原则:标签式设计: 圆角背景类似微信搜索历史Flex 布局: 自动换行适应不同屏幕文本溢出: 超长关键词显示省略号交互反馈: 删除按钮点击有高亮效果视觉层次: 标题灰色清空红色层次分明 测试验证功能测试测试场景操作步骤预期结果状态保存历史搜索聚餐历史记录显示聚餐✅去重再次搜索聚餐聚餐移到第一位✅限制10条搜索11个不同词只显示最近10条✅点击历史点击聚餐触发搜索显示结果✅删除单条点击 ✕ 按钮该条消失Toast提示✅清空全部点击清空历史二次确认后清空✅页面刷新退出再进入历史记录依然存在✅空关键词输入空格搜索不保存历史✅特殊字符搜索聚餐庆祝正常保存和显示✅首次使用新用户进入不显示历史区域✅性能测试指标目标值实际值状态保存耗时 10ms~5ms✅加载耗时 10ms~3ms✅UI 更新流畅无卡顿✅存储占用 1KB~500B✅⚠️ 踩坑记录问题1: 事件冒泡导致误触发现象: 点击删除按钮时同时触发了搜索原因: 删除按钮的点击事件冒泡到外层解决: 使用catchtap代替bindtap!-- ❌ 错误 --viewbindtaponDeleteHistoryItem!-- ✅ 正确 --viewcatchtaponDeleteHistoryItem问题2: 历史记录顺序不正确现象: 重复搜索同一关键词没有移到最前面原因: 只做了 unshift没有先 filter 去重解决: 先 filter 移除旧的再 unshift 添加新的// ❌ 错误history.unshift(keyword);// ✅ 正确historyhistory.filter(itemitem!keyword);history.unshift(keyword);问题3: 首次使用报错现象: 新用户首次进入页面控制台报错原因:wx.getStorageSync返回 undefined解决: 提供默认值空数组// ❌ 错误consthistorywx.getStorageSync(vote_search_history);// ✅ 正确consthistorywx.getStorageSync(vote_search_history)||[]; 技术要点总结微信小程序 Storage API同步 vs 异步// 同步推荐简单可靠wx.setStorageSync(key,value);wx.getStorageSync(key);wx.removeStorageSync(key);// 异步复杂场景wx.setStorage({key:key,data:value});wx.getStorage({key:key,success:...});存储限制单个 key 最大 1MB总存储最大 10MB我们的数据远小于限制生命周期存储在本地小程序卸载后清除用户手动清除缓存也会清除不会跨设备同步数组操作技巧去重并添加到头部historyhistory.filter(itemitem!keyword);history.unshift(keyword);限制数组长度if(history.length10){historyhistory.slice(0,10);}根据索引删除consthistory[...this.data.searchHistory];// 浅拷贝history.splice(index,1);事件处理最佳实践阻止冒泡!-- 内层事件使用 catchtap --viewbindtapouterHandlerviewcatchtapinnerHandler.../view/view传递数据viewdata-keyword{{item}}data-index{{index}}constkeyworde.currentTarget.dataset.keyword;constindexe.currentTarget.dataset.index;