设置 cookie, 获取 cookie, 删除 cookie 的封装

1. 设置 cookie 封装

function setCookie(key, value, expires){
    let now = new Date();
    now.setDate(now.getDate()+expires);
    document.cookie = `${key} = ${value}; expires= ${now.toUTCString()}`;
}

2. 提取 cookie 封装

function getCookie(){
    let obj = {};
    let cookies = document.cookie.split('; ');
    cookies.forEach(r => {
        let kv = r.split('=');
        let key = kv[0];
        let val = kv[1];
        obj[key] = val;
    });
    if(key){return obj[key]}
    return obj
}

3. 删除 cookie 封装

function removeCookie(key){
    setCookie(key, null, -1)
}

你可能感兴趣的:(设置 cookie, 获取 cookie, 删除 cookie 的封装)