高效管理搜索历史: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([])
    }
  }
}
相关推荐
u***u6859 小时前
React环境
前端·react.js·前端框架
X***E4639 小时前
前端数据分析应用
前端·数据挖掘·数据分析
4***14909 小时前
React社区
前端·react.js·前端框架
LFly_ice9 小时前
学习React-24-路由传参
前端·学习·react.js
Lhuu(重开版10 小时前
CSS:动效布局动画
前端·css
Q***K5510 小时前
前端构建工具
前端
laocooon52385788610 小时前
创建了一个带悬停效果的“我的个人主页“按钮
前端
2013编程爱好者11 小时前
Vue工程结构分析
前端·javascript·vue.js·typescript·前端框架
小满zs12 小时前
Next.js第十一章(渲染基础概念)
前端
不羁的fang少年13 小时前
前端常见问题(vue,css,html,js等)
前端·javascript·css