You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用VueUse useStorage存储最多10条搜索历史对象数组

使用@vueuse/core的useStorage实现最多10条搜索记录存储

实现思路

核心是利用useStorage绑定localStorage中的搜索记录数组,每次添加新记录时:

  1. 移除数组中与新记录重复的项(避免重复存储)
  2. 将新记录插入数组头部(保证最新记录优先展示)
  3. 截断数组,只保留前10条(控制存储数量上限)

具体代码实现

1. 导入依赖并定义类型

import { useStorage } from '@vueuse/core'

// 你的搜索记录类型定义
export type TSearchHistoryItem = {
  tab: string,
  inventory?: {
    id: number | null,
    name: string | null
  },
  keyword?: string | null,
  city: {
    id: number | null,
    name: string | null
  },
  radius: number | null,
  label?: string
}

2. 封装搜索记录操作逻辑

可在全局工具文件或组件内部定义:

// 初始化搜索记录数组,绑定到localStorage的'search-history'键
const searchHistory = useStorage<TSearchHistoryItem[]>('search-history', [])

// 添加搜索记录的方法
const addSearchHistory = (newItem: TSearchHistoryItem) => {
  // 1. 去重:移除和新记录核心参数匹配的旧项(可根据业务调整匹配规则)
  const filteredHistory = searchHistory.value.filter(item => {
    // 这里以tab、关键词、城市ID、半径为核心匹配字段,可按需修改
    return !(
      item.tab === newItem.tab &&
      item.keyword === newItem.keyword &&
      item.city.id === newItem.city.id &&
      item.radius === newItem.radius &&
      item.inventory?.id === newItem.inventory?.id
    )
  })

  // 2. 将新记录放到数组最前面
  filteredHistory.unshift(newItem)

  // 3. 截断数组,最多保留10条
  searchHistory.value = filteredHistory.slice(0, 10)
}

3. 在组件中使用

比如在搜索提交逻辑中调用:

// 假设这是用户提交的搜索参数
const handleSearchSubmit = () => {
  const newSearchItem: TSearchHistoryItem = {
    tab: 'goods',
    keyword: '手机',
    city: { id: 1, name: '北京' },
    radius: 5,
    inventory: { id: 1001, name: '数码产品' }
  }

  // 添加到搜索记录
  addSearchHistory(newSearchItem)

  // 执行其他搜索逻辑...
}

注意事项

  • 去重规则可根据业务需求灵活调整,比如仅按关键词去重
  • useStorage会自动完成数组与localStorage之间的序列化/反序列化,无需手动处理JSON转换
  • 若需要改用sessionStorage,只需给useStorage传入第三个参数:{ storage: sessionStorage }

内容的提问来源于stack exchange,提问作者zoltalar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 13:20:03