vue 前端本地保存搜索历史,localStorage
一、保存历史的数组是由元素组成: [ “000004 SZ”]
- 在页面第一次加载的时候,从localStorage中获取历史记录
created() {
//获取localstorage
let storage=window.localStorage;
if(storage.getItem('searchWord') !== null){
// _this.historyLis 为渲染到页面
_this.historyList = JSON.parse(storage.getItem('searchWord'));
}
}
2.在搜索功能的方法里调用下面的函数,将当前的记录存储到localStorage中
//item为你当前搜所输入的值
saveHistory(item){
let storage = window.localStorage;
//若无记录历史,直接将新的历史记录设置在localStorage中,若有记录历史,先判断数据是否超过5条,若超过五条 则取最新的五条,去除重复的记录
let val = item;
if(storage.getItem('searchWord') == null){
_this.historyList.unshift(item);
storage.setItem('searchWord',JSON.stringify(_this.historyList));
}else{
if(_this.historyList.indexOf(val) != -1){
_this.historyList.splice(_this.historyList.indexOf(val), 1);
_this.historyList.unshift(val);
}else{
_this.historyList.unshift(val);
}
if (_this.historyLis.length >= 5) _this.historyLis.pop()
storage.setItem('searchWord',JSON.stringify(_this.historyList));
}
}
二、保存历史的数组是有对象组成的: [ {number: “00700 HK”, name: “腾讯控股”},{number: “003816 SZ”, name: “中国广核”}]
思路和上方是一样的,只是在处理重复对象的问题的时候有些不一样
//在created()里获取localStorage的值
if (localStorage.getItem('searchHistory')) {
this.historyList = JSON.parse(localStorage.getItem('searchHistory'))
}
//存储当前记录
saveHistory(name, number) {
{
let temp = []
if (localStorage.getItem('searchHistory')) {
temp = JSON.parse(localStorage.getItem('searchHistory'))
if (temp.length >= 5) temp.pop()
let sameIndex = temp.findIndex((item, index) => {
return item.number === number
})
if (sameIndex >= 0) temp.splice(sameIndex, 1)
}
temp.unshift({ number, name})
localStorage.setItem('searchHistory', JSON.stringify(temp))
this.historyList = JSON.parse(localStorage.getItem('searchHistory'))
}
}
3.删除某条历史记录
deleteHistory (index) {
const temp = this.historyList
temp.splice(index, 1)
localStorage.setItem('searchHistory', JSON.stringify(temp))
this.historyList = JSON.parse(localStorage.getItem('searchHistory'))
},
4.清空历史记录
clearHistory(){
localStorage.clear();
}