说明
记录localstore在项目中的一些使用持续记录
个localstore加上过期时间
在现在web开发中,大量应用啦localstore,我们封装一个可以带过期功能的localstre这样,可以兼容cookie的使用,也可用了避免使用cookie
/**
* 数据使用localstore存储
*/
export const ls = {
//本地存数据,days 有效时间(天)
setItem: function(key, value, days) {
let Days = days || 7 //有效时间默认7天
let exp = new Date()
let expires = exp.getTime() + Days * 24 * 60 * 60 * 1000
localStorage.setItem(
key,
JSON.stringify({
value,
expires
})
)
},
getItem: function(key) {
let o = JSON.parse(localStorage.getItem(key))
if (o !== null && Date.now() < o.expires) {
return o.value
} else {
return null
}
},
removeItem: function(key) {
localStorage.removeItem(key)
},
clearAll: function () {
localStorage.clear()
}
}