Storage封裝

為什么要封裝Storage?

  • Storage本身有API,但只是簡(jiǎn)單的key / value 形式
  • Storage只存儲(chǔ)字符串,需要手動(dòng)轉(zhuǎn)化成json對(duì)象
  • Storage只能一次性清空,不能單個(gè)清空
//數(shù)據(jù)存儲(chǔ)
/**
 * Storage封裝
 */
const STORGE_KEY = 'mall'; // 定義一個(gè)key
export default {
    //存儲(chǔ)值
    setItem(key, value, module_name) {
        if (module_name) {
            let val = this.getItem(module_name);
            val[key] = value;
            this.setItem(module_name, val);
        } else {
            let val = this.getStorage();
            val[key] = value;
            window.sessionStorage.setItem(STORGE_KEY, JSON.stringify(val));
        }
    },

    //獲取某一個(gè)模塊下面的user下面的userName
    getItem(key, module_name) {
        if (module_name) {
            let val = this.getItem(module_name);
            if (val) return val[key];
        }
        return this.getStorage()[key];
    },

    // 獲取整個(gè)數(shù)據(jù)
    getStorage() {
        return JSON.parse(window.sessionStorage.getItem(STORGE_KEY) || '{}');
    },

    //清空某一個(gè)值
    clear(key, module_name) {
        let val = this.getStorage();
        if (module_name) {
            delete val[module_name][key];
        } else {
            delete val[key];
        }
        window.sessionStorage.setItem(STORAGE_KEY, JSON.stringify(val));
    },
};
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容