设置cookie
function setCookie(name, value,days) {
//三个参数,一个是cookie的名子,一个是值,最后一个是天数
var exp = new Date(); //new Date("December 31, 9998");
exp.setTime(exp.getTime() + days * 24 * 60 * 60 * 1000);
document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString();
}
读取cookie
function getCookie(name) {
//取cookies函数
var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
if (arr != null)
return unescape(arr[2]);
return null;
}
删除cookie
function delCookie(name){
//删除cookie并重新演示
// 该函数检查下cookie是否设置,如果设置了则将过期时间调到过去的时间;
//剩下就交给操作系统适当时间清理cookie啦
if (getCookie(name)){
document.cookie = name + "=" + "; expires=Thu, 01-Jan-70 00:00:01 GMT";
}
}
简洁写法
1.封装在methods.js中
cookie示例:
token=eyJhbyZn8b3kkqeCIFw311pAp1IQMLwRw; Max-Age=7200; Expires=Fri, 05-Nov-2021 04:43:22 GMT; Path=/
class cookie {
static get(k) {
return ((new RegExp(["(?:; )?", k, "=([^;]*);?"].join(""))).test(document.cookie) && RegExp["$1"]) || "";
}
static set(k, v, e, d) {
document.cookie = [k, "=", v, e && e["toGMTString"] ? ';expires=' + e.toGMTString() : "", ";path=/;domain=", d || ""].join("");
}
static del(k) {
document.cookie = k + '=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/'
}
}
export { cookie };
2.在使用的vue文件中引入使用
import {cookie} from '@/tools/methods'
cookie.get('token')
cookie.set('token','123456')
cookie.del('token')