基于tslocalstorage的二次封装带过期时间

import dayjs from 'dayjs';
const writeTime = dayjs().unix() // 存入时间
const expired = 30

//dayjs是一个只有2kb 的时间插件
//  dayjs().unix() 获取的是秒所以 expired  设置为s 

export function setItems (key:string, value:any) {
  const Obj = { value, writeTime , expired}
  localStorage.setItem(key, JSON.stringify(Obj));
}

export function getItems (keys:string){
  const dataJson = localStorage.getItem(keys)
  if(dataJson === null || typeof dataJson === 'undefined'){
    return
  }
  const data = JSON.parse(dataJson)
  const readTime = dayjs().unix();
  if((readTime - data.writeTime) > data.expired){
    // 数据过期 清除数据
    localStorage.removeItem(keys);
    return
  }else{
    console.log(readTime - data.writeTime)
    return data.value
  }
}

export function removeItem(keys:string){
  localStorage.removeItem(keys);
  return true
}

export function clearAll(){
  localStorage.clear()
  return true
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容