搜索历史记录功能--利用缓存实现
思路:
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
}
})
}
}