持久化存储

// 短时存储写入
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);
}

使用示例

人生到处知何似,应似飞鸿踏雪泥。
原文地址:https://www.cnblogs.com/lepanyou/p/15419347.html