搜索功能在商品很多的时候尤为重要,那为什么要历史记录呢,是在乎用户的感受,节约用户思路和操作的时候而产生的一项新的功能,那我们就来讨论一些历史记录是怎么实现的?
首先我们来对比一下localStorage和sessionStorage:
localStorage生命周期是永久,这意味着除非用户显示在浏览器提供的UI上清除localStorage信息,否则这些信息将永远存在。
sessionStorage生命周期为当前窗口或标签页,一旦窗口或标签页被永久关闭了,那么所有通过sessionStorage存储的数据也就被清空了。
不同浏览器无法共享localStorage或sessionStorage中的信息。相同浏览器的不同页面间可以共享相同的localStorage(页面属于相同域名和端口),但是不同页面或标签页间无法共享sessionStorage的信息。
由此看来localStorage更加适合我们做历史记录,即使用户关闭浏览器操作,下次进来依旧存在。
localStorage的操作也是极其简单的:
// Save data to the current local store localStorage.setItem("username", "John"); // Access some stored data alert( "username = " + localStorage.getItem("username")); // 或者直接对象操作: localStorage.historyItems = '历史记录'; console.log(localStorage.historyItems) // 历史记录
搜索历史记录展现形式:
V1版:
// 当为空的时候设置一个关键字进去,判断如果关键字是否存在,不存在就追加新的关键字
setHistoryItems(keyword) {
let { historyItems } = localStorage;
if (historyItems === undefined) {
localStorage.historyItems = keyword;
} else {
const isNotExists = historyItems.split('|').filter((e) => e == keyword).length == 0;
if (isNotExists) localStorage.historyItems += '|' + keyword;
}
}
V2版:
// 判断关键字是否存在,存在就移除添加在首位 setHistoryItems(keyword) { let { historyItems } = localStorage; if (historyItems === undefined) { localStorage.historyItems = keyword; } else { let historyItems = historyItems.split('|'); const isExists = historyItems.filter(e => e == keyword).length > 0; if (isExists) { historyItems = keyword + '|' + historyItems.filter(e => e != keyword).join('|'); } else { historyItems += '|' + keyword; } localStorage.historyItems = historyItems; } }
终极版:
// 不管关键字是否存在都移除,新的关键字添加在首位 setHistoryItems(keyword) { let { historyItems } = localStorage; if (historyItems === undefined) { localStorage.historyItems = keyword; } else { historyItems = keyword + '|' + historyItems.split('|').filter(e => e != keyword).join('|'); localStorage.historyItems = historyItems; } }
再次更正版:解决只有一个关键字历史记录出现空记录
// 过滤一个结果的空记录添加,过滤空搜索 setHistoryItems(keyword) { keyword = keyword.trim(); let { historyItems } = localStorage; if (historyItems === undefined) { localStorage.historyItems = keyword; } else { const onlyItem = historyItems.split('|').filter(e => e != keyword); if (onlyItem.length > 0) historyItems = keyword + '|' + onlyItem.join('|'); localStorage.historyItems = historyItems; } }
清除历史记录关键字:
clearHistory() { localStorage.removeItem('historyItems'); }