高效管理搜索历史: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([])
    }
  }
}
相关推荐
陈天伟教授2 小时前
人工智能训练师认证教程(2)Python os入门教程
前端·数据库·python
信看3 小时前
NMEA-GNSS-RTK 定位html小工具
前端·javascript·html
Tony Bai3 小时前
【API 设计之道】04 字段掩码模式:让前端决定后端返回什么
前端
爱吃大芒果3 小时前
Flutter 主题与深色模式:全局样式统一与动态切换
开发语言·javascript·flutter·ecmascript·gitcode
苏打水com3 小时前
第十四篇:Day40-42 前端架构设计入门——从“功能实现”到“架构思维”(对标职场“大型项目架构”需求)
前端·架构
king王一帅3 小时前
流式渲染 Incremark、ant-design-x markdown、streammarkdown-vue 全流程方案对比
前端·javascript·人工智能
苏打水com3 小时前
第十八篇:Day52-54 前端跨端开发进阶——从“多端适配”到“跨端统一”(对标职场“全栈化”需求)
前端
Bigger4 小时前
后端拒写接口?前端硬核自救:纯前端实现静态资源下载全链路解析
前端·浏览器·vite
BD_Marathon4 小时前
【JavaWeb】路径问题_前端绝对路径问题
前端