本地存储设置数据过期时间

165 阅读1分钟
export default class Storage{
	constructor(expiryTime){
		this.expiryTime = expiryTime
	}
	set(key,value,expiryTime){
		let obj = {
			data:value,
			expiryTime:Date.now() + (expiryTime || this.expiryTime)
		}
		localStorage.setItem(key,JSON.stringify(obj))
	}
	get(key){
		let item = localStorage.getItem(key)
		if(!item) return null
		item = JSON.parse(item)
		let nowTime = Date.now()
		if(item.expiryTime && nowTime > item.expiryTime){
			//过期
			this.remove(key)
			return null
		}else{
			return item.data
		}
	}
	remove(key){
		localStorage.removeItem(key)
	}
	clear(){
		localStorage.clear()
	}
}

使用:

import Storage from 'xx/storage.js'
const operateStorage = new Storage(24*60*60*1000) //设置全局过期时间为24小时,不设置全局过期时间可不传该参数’
operateStorage.set('token','toekn989868761273') //使用全局过期时间版

const operateStorage = new Storage()  //不设置全局过期时间
operateStorage.set('token','toekn989868761273',60*1000) //设置独立的过期时间为1分钟
operateStorage.set('token','toekn989868761273') //不设置独立的过期时间,既不设置全局过期时间,又不设置独立过期时间,即无过期时间