封装自己的cookie设置和获取的方法

项目中对cookie的操作是比较频繁的,因此我们封装起来一个方法供调用。
我们采用ES6封装为一个js,供外界引入调用。

let cookie = document.ccokie,
    encode = encodeURIComponent,
    decode = decodeURLComponent;
export default {
    // 获取cookie
    get (key) {
    	// 下面的正则:若要找的key在第一个,需要匹配开头;若不是第一个,一定是以空格开头的
        let reg = new RegExp('(?:^| )' + encode(key) + '=([^;]+)');
        let result = cookie.match(reg);
        return result && decode(result[1]);
    },
    set (key, value, expires, domain, path, excure) {
        //设置cookie时,过期时间提供单位为天,如果没有给,那么默认过期时间是一天。
        // 域名没有给,会设置到当前地址的顶级域名下,各个子域名均可使用
        cookie = encode(key) + '=' + encode(value) + '; expires=' + new Date((new Date + (typeof expires !== 'undefined' ? expires : 1)) * 24 * 60 * 60).toGMTString() + '; path=' + path ? path : '/' +'; domain=' + domain ? domain : document.domain.splict('.').slice(-2).join('.') + '; execure=' + excure;
    },
    remove (key,domain, path, execure) {
        this.set(key, '', 0, domain, path, execure);
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值