首页 > 其他分享 >JS存储

JS存储

时间:2023-01-08 01:22:05浏览次数:32  
标签:存储 Storage Cache storage value JS key

Storage

localStorage

永久性的存储方法

  • 属性
    • length
  • 方法
    • Storage.key(index): 返回存储中的第n个key名称
    • Storage.getItem(key)
    • Storage.setItem(key,value)
    • Storage.removeItem(key)
    • Storage.clear()

sessionStorage

临时存储方法,会话关闭,存储内容会被清除

  • getItem(key)
  • setItem(key,value)

Storage封装

class Cache {
    constructor(isLocal = true){
        this.storage = isLocal?localStorage:sessionStorage
    }
    setCache(key,value){
        if (!value) {
            throw new Error('value error: value 必须有值')
        }
        this.storage.setItem(key,JSON.stringify(value))
    }
    getCache(key){
        const result = this.storage.getItem(key)
        if(result){
            return JSON.parse(result)
        }
    }
    removeCache(key){
        this.storage.removeItem(key,value)
    }
    clear(key,value){
        this.storage.clear()
    }
}
const localCache = new Cache()
const sessionCache = new Cache(false)

cookie

标签:存储,Storage,Cache,storage,value,JS,key
From: https://www.cnblogs.com/hyf120/p/17033985.html

相关文章