CookieUtil.js
const CookieUtil={
get(name){
let cookieName=encodeURIComponent(name)+"=",
cookieStart=document.cookie.indexOf(cookieName),
cookieValue=null;
if(cookieStart>-1){
let cookieEnd=document.cookie.indexOf(";",cookieStart);
if(cookieEnd==-1){
cookieEnd=document.cookie.length;
}
cookieValue=decodeURIComponent(document.cookie.substring(cookieStart+cookieName.length,cookieEnd));
}
return cookieValue;
},
set(name,value,expires,path,domain,secure){
let cookieText=encodeURIComponent(name)+"="+encodeURIComponent(value);
if(expires instanceof Date){
cookieText+="; expires="+expires.toGMTString();
}
if(typeof expires==="string"){
let time = this.getsec(expires);
let exp = new Date();
exp.setTime(exp.getTime() + time*1);
cookieText+="; expires="+exp.toGMTString();
}
if(path){
cookieText+="; path="+path;
}
if(domain){
cookieText+="; domain="+domain;
}
if(secure){
cookieText+="; secure";
}
document.cookie=cookieText;
},
//这是有设定过期时间的使用示例:
//20s是代表20秒
//h是指小时,如12小时则是:12h
//d是天数,30天则:30d
getsec: function (str) {
let str1=str.substring(0,str.length-1)*1;
let str2=str.substring(str.length-1,str.length);
if (str2=="s")
{
return str1*1000;
}
else if (str2=="h")
{
return str1*60*60*1000;
}
else if (str2=="d")
{
return str1*24*60*60*1000;
}
},
unset(name,path,domain,secure){
this.set(name,"",new Date(0),path,domain,secure);
}
};
export default CookieUtil;
使用方法:
CookieUtil.set("myname","angle","20h",null,null,false);
console.log(CookieUtil.get("myname")) ;
CookieUtil.unset("myname",null,null,false);