封装带过期时间的localStorage

// 封装一个localStorage函数,减少页面请求
export function Storage() {
    if (!window.localStorage) {
        // 这里应该走cookie逻辑
        alert('此版本浏览器不支持本地存储')
        return false
    }
    return {
        set(key, obj, outtime) {
            let ctime = parseInt(Date.now() / 1000) //获取存数据的时间
            let exp = outtime || 24 * 60 * 60//outtime 是 秒为单位的过期时间
            let outObj = { // 时间和数据
                outime: ctime + exp,
                data: obj
            }
            localStorage.setItem(key, JSON.stringify(outObj))
        },
        get(key) {
            let data = JSON.parse(localStorage.getItem(key))
            //初始化没有数据
            if (!data) { return false }
            //判断过期时间 和获取数据的时间对比 大于过期时间说明超时
            if (data.outime >= parseInt(Date.now() / 1000)) {
                return data.data
            } else {
                return false
            }
        }
    }
}

你可能感兴趣的:(杂七杂八,js,vue,封装,localStorage,过期时间)