vue搜索历史记录缓存实现
思路:
1.浏览器缓存永久保存搜索历史数据.
2.页面初始化将数据保存到页面变量中.
3.对搜索历史记录的怎加和删除,要同步到缓存中.
----------------直接看代码----------------
*前端使用的是vue,这里只是代码片段*
1.页面的 div
<!---历史搜索begin----> <div style="margin-top: 46px"> <div v-if="this.showFlag === true" class="search-history"> <div class="tip-words"> <div style="float: left;"> <h4>搜索历史</h4> </div> <div style="float: right;" @click="clearHistoryItems"> <img src="../../img/img/delete-1.png" width="16px"/> </div> </div> <p style="margin-bottom: 10px"> </p> <div v-for="(item,index) in searchHistoryList" :key="index" @click="searchByHistoryKeyWord(item)" class="history-keywords"> {{item}} </div> </div> </div> <!---历史搜索end---->
2. vue data
data() { return { // 搜索历史 searchHistoryList: [], // 标记显示搜索历史 showFlag: false, loadShow: false } },
3.vue 搜索历史的一些方法
methods: { showHistory() { if (this.searchHistoryList.length > 0) { this.showFlag = true } }, // 清空历史记录 clearHistoryItems() { localStorage.removeItem('historyItems') this.searchHistoryList = [] this.showFlag = false }, // 过滤一个结果的空记录添加,过滤空搜索 appendKeywords(value) { /** * 1.已经有的关键词不再添加 * 2.添加到数组的首位,若超出10个则删除最后一个 * 3.添加到缓存 */ var appendFlag = true if (this.searchHistoryList !== null && this.searchHistoryList !== undefined && this.searchHistoryList.length > 0) { this.searchHistoryList.forEach(function(currentValue, index) { if (currentValue === value) { appendFlag = false return } }) // 判断-添加 if (appendFlag === true) { // 长度判断 if (this.searchHistoryList.length >= 10) { this.searchHistoryList.unshift(value) this.searchHistoryList.pop() } else { this.searchHistoryList.unshift(value) } localStorage.setItem('historyItems', JSON.stringify(this.searchHistoryList)) } } else { this.searchHistoryList = [] this.searchHistoryList.push(value) localStorage.setItem('historyItems', JSON.stringify(this.searchHistoryList)) } }, searchByHistoryKeyWord(item) { this.loadTip = '' this.queryData.inputInfo = item // 查询 fetchGetDataByKeyWord(item).then(response => { // 查询赋值 this.dataList = response.data.body.data if (this.dataList.length === 0) { this.loadTip = '没有符合条件数据' this.showHistory() } else { this.loadTip = '' this.showFlag = false } }) } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)