storage 二次封装

    在项目的 utils 目录下,创建一个名为 storage.ts 的文件,用于封装对 localStorage 的操作。

    1/**
    2 * Storage 二次封装
    3 */
    4
    5const namespace = "vue3-admin";
    6
    7interface StorageItem {
    8  [key: string]: any;
    9}
    10
    11interface StorageInterface {
    12  getStorage(): StorageItem;
    13  setItem(key: string, value: any): void;
    14  getItem(key: string): any;
    15  removeItem(key: string): void;
    16  clear(): void;
    17}
    18
    19const storage: StorageInterface = {
    20  getStorage() {
    21    return JSON.parse(window.localStorage.getItem(namespace) || "{}");
    22  },
    23  setItem(key, value) {
    24    const storage = this.getStorage();
    25    storage[key] = value;
    26    window.localStorage.setItem(namespace, JSON.stringify(storage));
    27  },
    28  getItem(key) {
    29    return this.getStorage()[key];
    30  },
    31  removeItem(key) {
    32    const storage = this.getStorage();
    33    delete storage[key];
    34    window.localStorage.setItem(namespace, JSON.stringify(storage));
    35  },
    36  clear() {
    37    window.localStorage.clear();
    38  },
    39};
    40
    41export default storage;