es封装cookie工具类

CookieUtil.js

const CookieUtil={
    get(name){
        let cookieName=encodeURIComponent(name)+"=",
            cookieStart=document.cookie.indexOf(cookieName),
            cookieValue=null;
        if(cookieStart>-1){
            let cookieEnd=document.cookie.indexOf(";",cookieStart);
            if(cookieEnd==-1){
                cookieEnd=document.cookie.length;
            }
            cookieValue=decodeURIComponent(document.cookie.substring(cookieStart+cookieName.length,cookieEnd));
        }
        return cookieValue;
    },
    set(name,value,expires,path,domain,secure){
        let cookieText=encodeURIComponent(name)+"="+encodeURIComponent(value);
        if(expires instanceof Date){
            cookieText+="; expires="+expires.toGMTString();
        }
        if(typeof expires==="string"){
            let time = this.getsec(expires);
            let exp = new Date();
            exp.setTime(exp.getTime() + time*1);
            cookieText+="; expires="+exp.toGMTString();
        }
        if(path){
            cookieText+="; path="+path;
        }
        if(domain){
            cookieText+="; domain="+domain;
        }
        if(secure){
            cookieText+="; secure";
        }
        document.cookie=cookieText;
    },
    //这是有设定过期时间的使用示例:
    //20s是代表20秒
    //h是指小时,如12小时则是:12h
    //d是天数,30天则:30d
    getsec: function (str) {
        let str1=str.substring(0,str.length-1)*1;
        let str2=str.substring(str.length-1,str.length);
        if (str2=="s")
        {
            return str1*1000;
        }
        else if (str2=="h")
        {
            return str1*60*60*1000;
        }
        else if (str2=="d")
        {
            return str1*24*60*60*1000;
        }
    },
    unset(name,path,domain,secure){
        this.set(name,"",new Date(0),path,domain,secure);
    }
};
export default CookieUtil;
使用方法:

CookieUtil.set("myname","angle","20h",null,null,false);
console.log(CookieUtil.get("myname")) ;
CookieUtil.unset("myname",null,null,false);




  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值