首页
归档
笔记
树洞
搜索
友言

文章详情

Interesting People Record Interesting.

/ JavaScript / 文章详情

js历史记录

Sonder
2021-12-08
1071字
3分钟
浏览 (2.9k)

复制代码
<div class="hljs"><code class="lang-js"><span class="hljs-comment">/**
 * 最近浏览
 * @param item 游戏列表
 */</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> newViewEnum = <span class="hljs-number">99</span>; <span class="hljs-comment">// 游戏栏目"最近浏览"的ID,是为了选中效果</span>
<span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">setHistoryList</span>(<span class="hljs-params">item</span>) </span>{
    <span class="hljs-keyword">const</span> newViewNum = <span class="hljs-number">8</span>; <span class="hljs-comment">// 显示历史记录条数</span>
    <span class="hljs-keyword">let</span> HistoryList = [];
    <span class="hljs-keyword">if</span>(<span class="hljs-built_in">window</span>.localStorage.getItem(<span class="hljs-string">'HistoryList'</span>) && <span class="hljs-built_in">window</span>.localStorage.getItem(<span class="hljs-string">'HistoryList'</span>) !== <span class="hljs-string">'[""]'</span>) {
        <span class="hljs-keyword">let</span> newHistoryList = <span class="hljs-built_in">JSON</span>.parse(<span class="hljs-built_in">window</span>.localStorage.getItem(<span class="hljs-string">'HistoryList'</span>));
        <span class="hljs-keyword">let</span> newArr = HistoryList.concat(newHistoryList)
        <span class="hljs-keyword">if</span> (newArr.length > <span class="hljs-number">0</span>) {
            newArr.map(<span class="hljs-function">(<span class="hljs-params">vo,key</span>) =></span> {
                <span class="hljs-keyword">if</span>(vo.id === item.id) {
                    newArr.splice(key, <span class="hljs-number">1</span>)
                }
            })
        }
        newArr.unshift(item)
        <span class="hljs-keyword">if</span> (newArr.length > newViewNum) {
            newArr.pop();
        }
        <span class="hljs-built_in">window</span>.localStorage.setItem(<span class="hljs-string">'HistoryList'</span>, <span class="hljs-built_in">JSON</span>.stringify(newArr))
    } <span class="hljs-keyword">else</span> {
        HistoryList.push(item);
        <span class="hljs-built_in">window</span>.localStorage.setItem(<span class="hljs-string">'HistoryList'</span>, <span class="hljs-built_in">JSON</span>.stringify(HistoryList))
    }
}
</code></div>

使用方法:

复制代码
<div class="hljs"><code class="lang-js">gotoPage(item) {
    setHistoryList(item);
    <span class="hljs-keyword">this</span>.$router.push({<span class="hljs-attr">path</span>: <span class="hljs-string">'/goodsList'</span>});
},
</code></div>
下一篇 / Google 和 Baidu 的 16 个高级搜索技巧

🎯 相关文章

💡 推荐文章

🕵️‍♂️ 评论 (0)