前端本地缓存:封装localStorage支持设置过期时间、命名空间


      - 当选中项目后,每隔5秒缓存一次当前页面所填内容       - 缓存至localStorage中,过期时间为7日,到期后自动删除当前项目的缓存,namespace为【visitPlanList】       - 中途退出软件时,下次进入新增页,选中之前的项目,会回显对应的内容       - 如果手动点击【放弃】按钮,并确认退出,那么会根据当前选中的项目id,删除对应的缓存       - 新增提交时,以本次提交时的项目id为依据,将visitPlanList中对应的缓存删除       - 缓存仅针对新增,编辑时不操作缓存,具体代码见@/views/Application/VisitManage/Plan/Add/index.vue

1、utils/index.js中定义myLocalStorage ,支持设置、获取、删除

// 拜访管理-前端缓存 namespace:命名空间,visitPlanList=拜访计划  visitFeedbackList=拜访反馈
export const myLocalStorage = {
  set(namespace = 'visitPlanList', key, data, time) {
    const storage = JSON.parse(localStorage.getItem(namespace)) || {}
    storage[key] = {
      data,
      createTime: Date.now(),
      lifeTime: time || 1000 * 60 * 60 * 24 * 7 // 默认设置过期时间:7天
    }
    localStorage.setItem(namespace, JSON.stringify(storage))
  },
  get(namespace = 'visitPlanList', key) {
    const storage = JSON.parse(localStorage.getItem(namespace)) || {}
    if (!storage[key]) return
    const { data, createTime, lifeTime } = storage[key]
    // 当前时间 - 存入时间 > 过期时间
    if (Date.now() - createTime > lifeTime) {
      delete storage[key]
      localStorage.setItem(namespace, JSON.stringify(storage))
      return null
    } else {
      return data
    }
  },
  delete(namespace = 'visitPlanList', key) {
    const storage = JSON.parse(localStorage.getItem(namespace)) || {}
    if (!storage[key]) return
    delete storage[key]
    localStorage.setItem(namespace, JSON.stringify(storage))
  }
}

2、页面使用

import { myLocalStorage } from '@/utils'
    // 存储缓存数据
    setStorage() {
      if (this.id) return
      const timer = setInterval(() => {
        const page1Data = this.$refs.page1Ref.page1Data
        if (page1Data.projectId <= 0) return
        const params = { page1Data, page2Data: this.page2Data }
        myLocalStorage.set('visitPlanList', page1Data.projectId, params)
      }, 5000)
      this.$once('hook:beforeDestroy', () => {
        clearInterval(timer)
      })
    },
    // 获取缓存数据
    getStorage(projectId) {
      if (this.id) return
      const params = myLocalStorage.get('visitPlanList', projectId)
      if (!params) return
      this.$refs.page1Ref.page1Data = params.page1Data
      this.page2Data = params.page2Data
    },
    // 删除缓存数据
    deleteStorage() {
      if (this.id) return
      const projectId = this.$refs.page1Ref.page1Data.projectId
      const params = myLocalStorage.get('visitPlanList', projectId)
      if (params) myLocalStorage.delete('visitPlanList', projectId)
    }

存储的数据结构:

vue