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.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
2.localStorage
配合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{
width: 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>
cookie、localStorage、sessionStorage及三者的区别
原文:https://www.cnblogs.com/94-Lucky/p/13439703.html