信息存储

/* 存储管理 */
const STORAGE_PREFIX = "text_";
// token,登录人信息,病人信息、主菜单、主题
const keyList = ["token", "userInfo", "info", "menus", "dataTheme"]; //可以在此声明使用的缓存,如不声明提示错误
// 会话存储 window.sessionStorage
function mySession() {
    
    
  this.setItem = function(name, content) {
    
    
    if (keyList.indexOf(name) == -1) {
    
    
      console.error(name + ":未声明,来自缓存管理,请在keyList中添加" + name);
      return;
    }
    if (typeof content == "object") {
    
    
      content = JSON.stringify(content);
    } else {
    
    
      content = String(content);
    }
    window.sessionStorage.setItem(STORAGE_PREFIX + name, content);
  };
  this.getItem = function(name, type) {
    
    
    console.log(name, type);
    try {
    
    
      if (type == "JSON") {
    
    
        return JSON.parse(window.sessionStorage.getItem(STORAGE_PREFIX + name));
      } else {
    
    
        return window.sessionStorage.getItem(STORAGE_PREFIX + name);
      }
    } catch {
    
    
      return window.sessionStorage.getItem(STORAGE_PREFIX + name);
    }
  };
  this.removeItem = function(name) {
    
    
    window.sessionStorage.removeItem(STORAGE_PREFIX + name);
  };
  this.clear = function() {
    
    
    window.sessionStorage.clear();
  };
}
let session = new mySession();

// 本地存储 localStorage
function local() {
    
    
  this.setItem = function() {
    
    };
  this.getItem = function() {
    
    };
  this.removeItem = function() {
    
    };
  this.clear = function() {
    
    };
}
// 本地存储
// cookie存储
let aaa = 1;
function myCookie() {
    
    
  aaa++;
  console.log(aaa, "aaa");
  this.setItem = function(cname, cvalue, exdays = 7) {
    
    
    //名字 内容 时间
    var d = new Date();
    d.setTime(d.getTime() + exdays * 24 * 60 * 60 * 1000);
    var expires = "expires=" + d.toGMTString();
    document.cookie = STORAGE_PREFIX + cname + "=" + cvalue + "; " + expires;
  };
  this.getItem = function(name) {
    
    
    let strcookie = document.cookie; //获取cookie字符串
    let arrcookie = strcookie.split("; "); //分割 //遍历匹配
    for (let i = 0; i < arrcookie.length; i++) {
    
    
      let arr = arrcookie[i].split("=");
      if (arr[0] == STORAGE_PREFIX + name) {
    
    
        return arr[1];
      }
    }
    return "";
  };
  this.removeItem = function(cname) {
    
    
    //名字 内容 时间
    document.cookie = STORAGE_PREFIX + cname + "=''; ";
  };
  this.clear = function() {
    
    
    let strcookie = document.cookie; //获取cookie字符串
    let arrcookie = strcookie.split("; "); //分割 //遍历匹配
    for (let i = 0; i < arrcookie.length; i++) {
    
    
      let arr = arrcookie[i].split("=");
      document.cookie = arr[0] + "=''; ";
    }
  };
}
let cookie = new myCookie();

// 存储缓存 setItem
// 获取缓存 getItem
// 清空缓存 removeItem
// 清空所有缓存 clear
export default {
    
    
  session,
  cookie
};

Guess you like

Origin blog.csdn.net/QZ9420/article/details/115293327