Cookies方法封装
在使用cookies的时候,使用原生的方法经常会不方便,这里做了一个封装。
export const Cookie = {
set(name, value, expiredays) {
let exdate = new Date();
exdate.setDate(exdate.getDate() + expiredays);
document.cookie = name + "=" + escape(value) + ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString());
},
get(name) {
let arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
if (arr = document.cookie.match(reg))
return (arr[2]);
else
return null;
},
remove(name) {
let exp = new Date();
exp.setTime(exp.getTime() - 1);
let cval = this.get(name);
if (cval != null)
document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
},
/**
* @param {string} websiteDomain [当前网站主域]
*/
removeAll(websiteDomain) {
var keys = document.cookie.match(/[^ =;]+(?==)/g)
if (keys) {
for (var i = keys.length; i--;) {
document.cookie = keys[i] + '=0;path=/;expires=' + new Date(0).toUTCString() // 清除当前域名下的,例如:m.ratingdog.cn
document.cookie = keys[i] + '=0;path=/;domain=' + document.domain + ';expires=' + new Date(0).toUTCString() // 清除当前域名下的,例如 .m.ratingdog.cn
document.cookie = keys[i] + '=0;path=/;domain=' + websiteDomain + ';expires=' + new Date(0).toUTCString() // 清除一级域名下的或指定的,例如 .ratingdog.cn
}
}
}
}