Storage封装

Storage封装

Cookie,localStorage,sessionStorage三者的区别?

  1. 共同点:都是保存在浏览器端、且同源的
  2. cookie数据始终在同源的http请求中携带(即使不需要),cookie在浏览器和服务器间来回传递;而sessionStorage和localStorage不会自动把数据发送给服务器,仅在本地保存。
  3. cookie数据还有路径限制,storage只存储在域名下。
  4. 存储大小:Cookie 4kb; storage 5M
  5. 有效期: sessionStorage:仅在当前浏览器窗口关闭之前有效;
    localStorage:始终有效,窗口或浏览器关闭也一直保存,因此用作持久数据;
    cookie:只在设置的cookie过期时间之前有效,即使窗口关闭或浏览器关闭 。
    6.Cookie没有特定的API,而storage有

为什么要封装Storage?

  • Storage本身有API,但只是简单的键值对
  • Storage只存储字符串,需要人工转换为json对象
  • Storage只能一次性清空,不能单个清空

Ctrl+Shift+I,Application
在这里插入图片描述

/*
*Storage封装
*/
const STORAGE_KEY = "mall";
export default{
  //存储值
  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(STORAGE_KEY,JSON.stringify(val));
    }
    
  },
  //获取某一模块下面的属性
  getItem(key,module_name){
    if (module_name) {
      let val = this.getItem(); //返回一个Object
      if (val) {
        return val[key];
      }
    }
    return this.getStorage()[key];
  },
  getStorage(){
    return JSON.parse(window.sessionStorage.getItem(STORAGE_KEY) || '{}')
  },
  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));
  }
}

然后再在APP.vue中import导入,再在mounted方法中引用

import storage from "./storage/index"


mounted(){
    storage.setItem('abnf',"1")
  }
原创文章 181 获赞 19 访问量 3万+

猜你喜欢

转载自blog.csdn.net/Pandora_417/article/details/105365533