基于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
}

你可能感兴趣的:(基于tslocalstorage的二次封装带过期时间)