cookie、localStorage、sessionStorage及三者的区别

cookie、localStorage、sessionStorage及三者的区别

1.语法

//写入cookie
document.cookie="name=morty";
document.cookie="name=wangchao"; //直接存储但cookie中,相同属性后面的会覆盖前面的
//cookie会随着浏览器的关闭而自动消失,想要不消失,可以设置时间
var date=new Date();
date.setMinutes(6);  //6分钟后过期,自动消失
document.cookie="name=xietian;expires="+date.toUTCString();  //必须是格林尼治时间
//手动删除cookie
document.cookie="name=morty;expires="+new Date();

2.如果想要设置多个cookie,按照上面的写法,显然麻烦,所以封装了简单的组件,以供使用

export default class Utils{
    constructor(){
        
    }
    //把cookie字符串转换为对象形式,获取到
    static getCookie(){
    return document.cookie.split(/;s*/).reduce((value,item)=>{
    var arr=item.split("=");
    value[arr[0]]=isNaN(arr[1]) ? arr[1] : Number(arr[1]);
    return value;
    },{})
    }
    //获取cookie具体属性 key是具体属性
    static getCookieValue(key){
    return Utils.getCookie()[key];
    }
    //key 属性 value 属性值 data 过期时间
    static setCookie(key,value,date){
    if(!date){
    document.cookie=`${key}=${value}`;
    return ;
    }
    document.cookie=`${key}=${value};expires=${date.toUTCString()}`;
    }
    //obj 对象 data 过期时间 以对象形式添加cookie
    static setCookies(obj,date){
    for(var key in obj){
    Utils.setCookie(key,obj[key],date);
    }
    }
    // 删除cookie具体某个属性
    static removeCookie(key){
    Utils.setCookie(key,"",new Date());
    }
    //清空cookie
    static clearCookie(){
    for(var key in Utils.getCookie()){
    Utils.removeCookie(key);
    }
    }
}

localStorage sessionStorage 语法相同

语法: 只能存储字符串

localStorage.name="morty";
localStorage.setItem("name","morty");
localStorage.getItem("name")
localStorage.removeItem("name");//删除某个数据
localStorage.clear();//清除所有数据
//想要一对象或者数组作为属性,先转换为字符串
var arr=[1,2,3];
localStorage.arr=JSON.stringify(arr);
var arr=JSON.parse(localStorage.arr);
console.log(arr);

三者区别

1.cookie

  • cookie会随着客户端向服务器发送请求时,自动发送cookie内存储的数据
  • cookie必须运行在服务器的环境下(开启服务器)
  • cookie的容量: 5kb
  • cookie存储的数据类型: 字符串
  • cookie存放以域名形式区分的。
  • 一个域名下存放的cookie的个数是有限制的,不同浏览器存放的个数不一样,cookie能存储的条目数为:50条。
  • 如果想长时间存放一个cookie,同时需要设置一个过期时间
  • Cookie默认是临时存储的,当浏览器关闭时,自动销毁

2.localStorage

  • 本地存储,用于持久化的本地存储,除非主动删除数据,否则数据是永远不会过期的;
  • localStorage 和 sessionStorage都是window对象的属性
  • 键值对方式进行存储,和map相同,有长度
    3.sessionStorage
  • 会话存储,用于本地存储一个会话 (session)中的数据,这些数据当在关闭浏览器后数据也随之销毁。
  • 同一个地址,后面打开的浏览器窗口不能获取 sessionStorage 数据

storage事件

配合localStorage可以实现跨页面操作
a.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button>red</button>
    <button>green</button>
    <button>blue</button>
    <script>
        bns=Array.from(document.querySelectorAll("button"));
        bns.forEach(item=>{
            item.addEventListener("click",clickHandler);
        })

        function clickHandler(e){
            localStorage.bgc=this.textContent;
        }
    </script>
</body>
</html>

b.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div{
             100px;
            height: 100px;
            background-color: brown;
        }
    </style>
</head>
<body>
   <div></div>
   <script>
       var div=document.querySelector("div");
       window.addEventListener("storage",storageHandler);

       function storageHandler(e){
           if(e.key==="bgc"){   //e.key是localStorage的属性
               div.style.backgroundColor=e.newValue;  //e.newValue 新的属性
           }
       }
   </script>
</body>
</html>
                                                                                如果想要更多的学习资料,加好友10398975,免费送
原文地址:https://www.cnblogs.com/94-Lucky/p/13439703.html