高效管理搜索历史: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([])
    }
  }
}
相关推荐
小徐_233338 分钟前
Wot UI 2.2.0 发布:Button 新增 subtle,VideoPreview 预览体验继续增强
前端·微信小程序·uni-app
山河木马2 小时前
矩阵专题3-怎么创建投影矩阵(uProjectionMatrix)
javascript·webgl·计算机图形学
天蓝色的鱼鱼3 小时前
关于 CSS 你可能不知道的属性,但关键时刻很有用
前端·css
泯泷4 小时前
第 2 篇:设计第一套字节码:Opcode、Instruction 与 Constant Pool
前端·javascript·安全
妙码生花4 小时前
从 PHP 到 AI + Golang,程序员自救转型手记(十五):优化细节、网络请求封装
前端·后端·ai编程
泯泷4 小时前
第 1 篇:从 1 + 2 开始:亲手写出第一台 JSVM
前端·javascript·安全
团团崽_七分甜4 小时前
Spring Boot 核心知识点总结
前端
lichenyang4534 小时前
从一个按钮开始,理解 ASCF 框架到底在做什么
前端
古夕4 小时前
第三方 SSO 接入实践:redirect_uri 编码、回调一致性与跨项目联调
前端·vue.js