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]) returnconst { data, createTime, lifeTime } =storage[key] //当前时间 - 存入时间 > 过期时间 if (Date.now() - createTime >lifeTime) { deletestorage[key] localStorage.setItem(namespace, JSON.stringify(storage)) return null} else{ returndata } }, delete(namespace = 'visitPlanList', key) { const storage = JSON.parse(localStorage.getItem(namespace)) ||{} if (!storage[key]) return deletestorage[key] localStorage.setItem(namespace, JSON.stringify(storage)) } }
2、页面使用
import { myLocalStorage } from '@/utils'
//存储缓存数据 setStorage() { if (this.id) returnconst timer = setInterval(() =>{ const page1Data = this.$refs.page1Ref.page1Data if (page1Data.projectId <= 0) returnconst params = { page1Data, page2Data: this.page2Data } myLocalStorage.set('visitPlanList', page1Data.projectId, params) }, 5000) this.$once('hook:beforeDestroy', () =>{ clearInterval(timer) }) }, //获取缓存数据 getStorage(projectId) { if (this.id) returnconst params = myLocalStorage.get('visitPlanList', projectId) if (!params) return this.$refs.page1Ref.page1Data =params.page1Data this.page2Data =params.page2Data }, //删除缓存数据 deleteStorage() { if (this.id) returnconst projectId = this.$refs.page1Ref.page1Data.projectId const params = myLocalStorage.get('visitPlanList', projectId) if (params) myLocalStorage.delete('visitPlanList', projectId) }
存储的数据结构: