封装localStorage和sessionStorage存储工具类

封装localStorage和sessionStorage存储工具类

    <script>
        // 工具类
        class Cache{
            // 使用构造器,区分是 localStorage 还是 sessionStorage 存储
            constructor(isLocal = true){
                this.storage = isLocal ? localStorage : sessionStorage
            }

            setCache(key,value){
                // localStorage 本身不能存储对象类型的数据,所以要使用 JSON.stringify() 将对象转成字符串                
                this.storage.setItem(key,JSON.stringify(value))
            }
            getCache(key){
                const result = this.storage.getItem(key)
                // 因为存储时已经将对象转为字符串了,所以在获取时要使用 JSON.parse() 转回对象类型
                // 获取值时要将字符串类型的数据转为对象类型
                // 因为如果是 undefined 会报错,所以在这里加一个判断更严谨
                if(result){
                    return JSON.parse(result)
                }
            }
            removerCache(key){
                return this.storage.removeItem(key)
            }
            clear(){
                this.storage.clear()
            }
        }
        
        // Cache不传默认为 true ,就是 localStorage 存储
        const localCache = new Cache()

        // 使用工具类对象存储值
        const userInfo = {
            name:"why",
            nickname:"coderwhy",
            level:100,
            imgURL:"www.baidu.com"
        }
        localCache.setCache("userInfo",userInfo)
        console.log(localCache.getCache("userInfo"));

        // Cache 传 false ,就是 sessionStorage 存储
        const localCache2 = new Cache(false)        
        localCache2.setCache("sessionStorage","sdjfksdfsldl")

    </script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值