原生JS中的cookie的封装
function setCookie(key,value,days,path){
path = path || "/";
if(days){
var date = new Date();
date.setDate(date.getDate()+days);
document.cookie =encodeURIComponent(key) + "=" +encodeURIComponent(value) + ";expires=" + date+";path="+path;
}
else{
document.cookie =encodeURIComponent(key) + "=" +encodeURIComponent(value) +";path="+path;
}
}
function getCookie(key){
var cookieStr = document.cookie;
if(cookieStr){
var cookieList = cookieStr.split("; ");
for(var i = 0 ;i < cookieList.length;i++){
var cookie = cookieList[i];
var item = cookie.split("=");
var itemKey = item[0];
if(itemKey ==encodeURIComponent(key)){
return decodeURIComponent(item[1]);
}
}
return "";
}else{
return "";
}
}
页面的调用方法
setCookie("loginId", list["loginId"], 7);
let userid = getCookie("loginId");