class Storage {
get = (key) => {
let data = window.localStorage.getItem(key)
if (!data) {
return{
message:`你输入的${key}无效`,
value:null
}
}
let value = JSON.parse(data)
let now = new Date().getTime()
if (typeof value['_expire_'] === 'number' && value['_expire_'] < now) {
this.remove(key)
return {
message:`你的${key}已过期`,
value:null
}
}
return {
message:'成功!',
value:value.value
}
}
set = (key,value,expire) => {
let data = this.normalize(value,expire)
window.localStorage.setItem(key,JSON.stringify(data))
}
remove = (key) => {
if (key) {
// 删除
window.localStorage.removeItem(key)
return {
message:`你输入的${key}已清除`,
value:null
}
}
// 清空
window.localStorage.clear()
return {
message:"已清空",
value:null
}
}
normalize = (value,expire) => {
// 规范化数据
let data = {
value,
'_expire_':expire // 过期时间
}
return data
}
}
封装基于localStorage本地存储
最新推荐文章于 2024-08-29 20:45:01 发布