高效管理搜索历史: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([])
    }
  }
}
相关推荐
Hi_kenyon1 小时前
VUE3套用组件库快速开发(以Element Plus为例)二
开发语言·前端·javascript·vue.js
Irene19911 小时前
Vue 3 响应式系统类型关系总结(附:computed、props)
vue.js·props·响应式类型
起名时在学Aiifox1 小时前
Vue 3 响应式缓存策略:从页面状态追踪到智能数据管理
前端·vue.js·缓存
天若有情6731 小时前
校园二手交易系统实战开发全记录(vue+SpringBoot+MySQL)
vue.js·spring boot·mysql
计算机程序设计小李同学2 小时前
个人数据管理系统
java·vue.js·spring boot·后端·web安全
李剑一2 小时前
uni-app实现本地MQTT连接
前端·trae
EndingCoder2 小时前
Any、Unknown 和 Void:特殊类型的用法
前端·javascript·typescript
oden2 小时前
代码高亮、数学公式、流程图... Astro 博客进阶全指南
前端
GIS之路2 小时前
GDAL 实现空间分析
前端