高效管理搜索历史:Vue持久化实践

搜索-历史记录管理

需求:

1.搜索历史基本渲染

2.点击搜索(添加历史)

点击搜索按钮或底下历史记录,都能进行搜索

①若之前 没有 相同搜索关键字,则直接追加到最前面

②若之前已有相同搜索关键字,将该原有关键字移除,再追加

3.清空历史:添加清空图标,可以清空历史记录

4.持久化:搜索历史需要持久化,刷新历史不丢失

src\utils\storage.js

js 复制代码
const HISTORY_KEY = 'hm_shopping_history'

export const getHistoryList = () => {
  const result = window.localStorage.getItem(HISTORY_KEY)
  return result ? JSON.parse(result) : []
}

export const setHistoryList = (arr) => {
  window.localStorage.setItem(HISTORY_KEY, JSON.stringify(arr))
}

src\views\search\index.vue

js 复制代码
import { getHistoryList, setHistoryList } from '@/utils/storage'
export default {
  name: 'SearchIndex',
  data() {
    return {
      search: '',
      history: getHistoryList()
    }
  },
  methods: {
    goSearch(key) {
      const index = this.history.indexOf(key)
      if (index !== -1) {
        this.history.splice(index, 1)
        this.history.push(key)
      } else {
        this.history.unshift(key)
      }

      // 限制历史记录数量(可选)
      if (this.history.length > 10) {
        this.history = this.history.slice(0, 10)
      }

      // 持久化
      setHistoryList(this.history)
      // 跳转到搜索列表页
      this.$router.push(`/searchlist?search=${key}`)
    },
    clearHistory() {
      this.history = []
      setHistoryList([])
    }
  }
}
相关推荐
小码哥_常5 小时前
一套自己部署的 IM,客户端是同一份 Flutter
前端·后端
蜗牛攻城狮8 小时前
微前端四大方案选型对比与最佳实践:qiankun、micro-app、wujie、Module Federation
前端·微前端·qiankun·前端架构·micro-app·wujie
她说可以呀9 小时前
Vue插槽
前端·javascript·vue.js
qq_448011169 小时前
Vue + Jinja2两套模版与法冲突造成undefinedError
前端·javascript·vue.js
aixingpan10 小时前
aixingpan.cn API开发文档:前端查询夏令时和时区接口指南
前端·php
2601_9583529010 小时前
23.5×19mm 换掉一整条音频链?|A-68 集成了什么:ADC / DAC / 24.576MHz 时钟 / AEC / 波束降噪,主控仅需 6 根线
前端·音视频·ai降噪·回声消除·语音模块
志尊宝11 小时前
AI原生前端开发(039):AI辅助的Nuxt 4全栈开发
前端·vue.js·ai-native
FRing0312 小时前
JavaScript入门到精通三十二(深拷贝、浅拷贝、递归函数)
开发语言·前端·javascript
excel12 小时前
双 Token 与前端使用 Crypto 公私钥鉴权换 Token,哪种方案更好?
前端·后端
外收内放12 小时前
Python基础语法练习题(73)
java·前端·python