Vue项目搜索-历史记录管理

搜索-历史记录管理

目标:构建搜索页的静态布局,完成历史记录的管理

需求:

  • 搜索历史基本渲染
  • 点击搜索(添加历史)
    • 点击搜索按钮 或底下历史记录,都能进行搜索
    • 若之前没有相同搜索关键字,则直接追加到最前面
    • 若之前已有相同搜索关键字,将该原有关键字移除,在追加(相当于置顶)
  • 清空历史:添加清空图标,可以清空历史记录
  • 持久化:搜索历史需要持久化,刷新历史不丢失

定义storage 本地js文件

// 商品的key
const HISTORY_KEY = 'hm_shopping_history'
// 添加历史记录
export const addHistory = (goods) => {
  localStorage.setItem(HISTORY_KEY, JSON.stringify(goods))
}

// 获取历史记录
export const getHistory = () => {
  const defalut = []
  const result = localStorage.getItem(HISTORY_KEY)
  return result ? JSON.parse(result) : defalut
}
// 删除 历史记录
export const removeHistory = () => {
  localStorage.removeItem(HISTORY_KEY)
}

定义vuex模块

import { getHistory, addHistory } from '@/utils/storage'
const state = {
  // 个人权证相关
  // 从本地获取用户信息
  history: getHistory()
}
const mutations = {
  // 提供一个存储 history 的方法
  setHistory (state, obj) {
    state.history = obj
    // 将商品信息存储到本地
    addHistory(obj)
  }
}
const actions = {

}
const getters = {

}

// 对外暴露
export default {
  namespaced: true, // 开启命名空间,用于mapState 映射
  state,
  mutations,
  actions,
  getters
}

页面组件使用

<script>
import { getHistory, addHistory } from '@/utils/storage'
export default {
  name: 'SearchIndex',
  data () {
    return {
      search: '', // 输入框内容
      history: getHistory() // 历史记录
    }
  },
  methods: {
    // 搜索
    goSearch (key) {
      if (key === '') {
        this.$toast('请输入搜索内容')
        return
      }
      // console.log('点击了搜索:' + key)
      const index = this.history.indexOf(key)
      if (index !== -1) {
        // 说明数组中存在相同的历史记录,此时删除原有的关键字
        this.history.splice(index, 1)
      }
      // unshift 追加到数组第一个
      this.history.unshift(key)
      // 调用 localStorage.setItem(HISTORY_KEY, JSON.stringify(goods)),保存到本地
      addHistory(this.history)
      // 跳转到搜索列表页
      this.$router.push('/searchlist?search=' + key)
    },
    // 清空
    clear () {
      this.history = []
      addHistory(this.history)
    }
  }

}
</script>
posted @   自学Java笔记本  阅读(118)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示