持久化存储

// 短时存储写入
export function setSessionStorage(key,value){
    if(typeof value === 'string'){
        return window.sessionStorage.setItem(key,value);
    }
    else{
        return window.sessionStorage.setItem(key,JSON.stringify(value));
    }
}

// 短时存储读取
export function getSessionStorage(key){
    try{
        return JSON.parse(window.sessionStorage.getItem(key))
    }
    catch(e){
        return window.sessionStorage.getItem(key);
    }
}

// 清除短时存储数据
export function removeSessionStorage(key){
    return window.sessionStorage.removeItem(key);
}

// 永久存储写入
export function setLocalStorage(key,value){
    if(typeof value === 'string'){
        return window.localStorage.setItem(key,value);
    }
    else{
        return window.localStorage.setItem(key,JSON.stringify(value));
    }
}

// 永久存储读取
export function getLocalStorage(key){
    try{
        return JSON.parse(window.localStorage.getItem(key))
    }
    catch(e){
        return window.localStorage.getItem(key);
    }
}

// 清除永久存储数据
export function removeLocalStorage(key){
    return window.localStorage.removeItem(key);
}

使用示例

remove之后的是null

 

posted @ 2021-10-18 09:56  乐盘游  阅读(46)  评论(0编辑  收藏  举报