前端:兼容 cookie 和 localStorage 类,且可设置过期时限

前言

兼容 CookielocalStorage 两种方式,且都可设置过期时限;

初始化

init(type, timeOut)

参数

名称类型描述
typeString存储方式。支持 2 种类型:cookie(存储值最大为 4KB)、localStorage(存储值最大为 5M)
timeOutNumber过期时限。单位为小时,例如 7 * 24 为 7 天

返回

Booleantrue 表示初始化成功,false 表示已初始化;

示例

初始化方法 Storage.init ,仅第一次生效;

// 初始化为 localStorage 类型,7 天过期
Storage.init('localStorage', 7 * 24);

方法

set(key, val)

  • 保存;
  • 返回:无;
  • 参数如下:
名称类型描述
keyString唯一标识
valObject存储值

get(key)

  • 获取;
  • 返回:被存储的值,过期为 null
  • 参数如下:
名称类型描述
keyString唯一标识

remove(key)

  • 移除;
  • 返回:Booleantrue 成功,false 失败;
  • 参数如下:
名称类型描述
keyString唯一标识

exist(key)

  • 判断对象是否存在;
  • 返回:Booleantrue 存在,false 过期或移除;
  • 参数如下:
名称类型描述
keyString唯一标识

clear()

  • 清空全部;
  • 返回:无;
  • 参数:无;

示例

此处使用 Vue2.x

<template>
    <div>
        <button @click="onclick(0)">存储</button>
        <button @click="onclick(1)">获取</button>
        <button @click="onclick(2)">删除</button>
        <button @click="onclick(3)">清空</button>
        <button @click="onclick(4)">获取keys</button>

    </div>
</template>

<script>
import Storage from '../js/Storage'
export default {
    methods: {
        onclick(i) {
            switch (i) {
                case 0: {
                    Storage.set('my_test', true);
                    break;
                }                    
                case 1: {
                    let val = Storage.get('my_test', false);
                    console.log('my_test', val);
                    break;
                }
                case 2: {
                    Storage.remove('my_test');
                    break;
                }
                case 3: {
                    Storage.clear();
                    break;
                }      
                case 4: {
                    let keys = Storage.getKeys();
                    console.log('keys', keys);
                    break;
                }       
                default:
                    break;
            }
        }
    },
    mounted() {
        // 初始化
        Storage.init('localStorage');
        // Storage.init('cookie');
    }
}
</script>

真正的实现

文件 Storage.js,文件分三部分 MyCookieMyLocalStorageStorage

// 唯一key
const MY_KEYS = '_My_Storage_Keys'

class MyCookie {

    constructor() {
        this.keys = [MY_KEYS]
        this.lastTime = null
        let flag = false
        let name = `${MY_KEYS}=`
        let ca = document.cookie.split(';')
        for (let i = 0; i < ca.length; i++) {
            let c = ca[i].trim()
            if (c.indexOf(name) == 0)
                flag = true
        }
        this.keys = flag ? this.get(MY_KEYS) : []

    }

    getKeys() {
        return this.keys
    }

    setHistory(timeOut) {
        timeOut = timeOut || this.lastTime
        let d = new Date()
        d.setTime(d.getTime() + (timeOut * 60 * 60 * 1000))
        let expires = 'expires=' + d.toGMTString()
        document.cookie = `${MY_KEYS}=` + JSON.stringify({ data: this.keys }) + '; ' + expires
        this.lastTime = timeOut
    }

    set(key, val, timeOut) {
        let d = new Date()
        d.setTime(d.getTime() + (timeOut * 60 * 60 * 1000))
        let expires = 'expires=' + d.toGMTString()
        document.cookie = key + '=' + JSON.stringify({ data: val }) + '; ' + expires
        this.keys.indexOf(key) < 0 && this.keys.push(key) && this.setHistory(timeOut)
    }

    get(key) {
        if (!this.exist(key))
            return null

        let name = key + '='
        let ca = document.cookie.split(';')
        for (let i = 0; i < ca.length; i++) {
            let c = ca[i].trim()
            if (c.indexOf(name) === 0)
                return JSON.parse(c.substring(name.length, c.length)).data
        }
    }

    remove(key) {
        for (let i in this.keys) {
            if (key == this.keys[i]) {
                document.cookie = this.keys[i] + '=; expires=Thu, 01 Jan 1970 00:00:00 GMT'
                this.keys.splice(i, 1)
                this.setHistory()
                return true
            }
        }
        return false
    }

    exist(key) {
        let name = key + '='
        let ca = document.cookie.split(';')
        for (let i = 0; i < ca.length; i++) {
            let c = ca[i].trim()
            if (c.indexOf(name) === 0)
                return true
        }
        this.remove(key)
        return this.keys.indexOf(key) > -1
    }

    clear() {
        for (let i in this.keys) {
            document.cookie = this.keys[i] + '=; expires=Thu, 01 Jan 1970 00:00:00 GMT'
        }
        this.keys = [MY_KEYS]
        this.setHistory(0)
    }
}

class MyLocalStorage {

    constructor() {
        this.keys = [MY_KEYS];
        this.keys = localStorage.getItem(MY_KEYS) ? this.get(MY_KEYS) : [];
        for (let i in this.keys) {
            this.exist(this.keys[i]);
        }
    }

    getKeys() {
        return this.keys;
    }

    setHistory() {
        localStorage.setItem(MY_KEYS, JSON.stringify({ data: this.keys })) //转换成json字符串序列
    }

    set(key, val, timeOut) {
        let cur = new Date().getTime()
        localStorage.setItem(key, JSON.stringify({ data: val, time: cur, timeOut: timeOut })) //转换成json字符串序列
        this.keys.indexOf(key) < 0 && this.keys.push(key) && this.setHistory()
    }

    get(key) {
        if (!this.exist(key))
            return null

        let val = localStorage.getItem(key) //获取存储的元素
        let dataObj = JSON.parse(val) //解析出json对象
        if (dataObj.timeOut != null && (new Date().getTime() - dataObj.time > dataObj.timeOut * 60 * 60 * 1000)) //如果当前时间-减去存储的元素在创建时候设置的时间 > 过期时间
        {
            return null
        } else {
            return dataObj.data
        }
    }

    remove(key) {
        for (let i in this.keys) {
            if (key == this.keys[i]) {
                localStorage.removeItem(this.keys[i])
                this.keys.splice(i, 1)
                this.setHistory()
                return true
            }
        }
        return false
    }

    exist(key) {
        let val = localStorage.getItem(key) //获取存储的元素
        let dataObj = JSON.parse(val) //解析出json对象
        if (dataObj && dataObj.timeOut != null && (new Date().getTime() - dataObj.time > dataObj.timeOut * 60 * 60 * 1000)) //如果当前时间-减去存储的元素在创建时候设置的时间 > 过期时间
        {
            this.remove(key)
        }
        return this.keys.indexOf(key) > -1
    }

    clear() {
        for (let i in this.keys) {
            localStorage.removeItem(this.keys[i])
        }
        this.keys = [MY_KEYS]
        this.setHistory()
    }
}

class Storage {

    static init(type, timeOut) {
        // 仅初始化一次
        if (this.currentStorage) {
            return false;
        }

        this.type = type;
        this.timeOut = timeOut;
        this.storageFactory = {
            cookie: MyCookie,
            localStorage: MyLocalStorage,
        }
        this.currentStorage = new this.storageFactory[type]();

        return true;
    }

    static getKeys() {
        return this.currentStorage.getKeys()
    }

    static set(key, val) {
        this.currentStorage.set(`_My_Storage_${key}`, val, this.timeOut)
    }

    static get(key) {
        return this.currentStorage.get(`_My_Storage_${key}`);
    }

    static remove(key) {
        return this.currentStorage.remove(`_My_Storage_${key}`);
    }

    static exist(key) {
        return this.currentStorage.exist(`_My_Storage_${key}`);
    }

    static clear() {
        this.currentStorage.clear();
    }

}

export default Storage
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值