前端Cookie设置流程(推荐第二种)

1. 纯手写设置

 读取cookie:        

const cookieGet = (name: any) => {

    let arr = document.cookie.split('; ')

    for (let i = 0; i < arr.length; i++) {

        let arr2 = arr[i].split('=')

        if (arr2[0] === name) {

            return arr2[1]

        }

    }

    return ''
}

  存储cookie

const cookieSet = (key: string, value: string, expire: number) => {

    let now = new Date(new Date().valueOf() + expire * 3600000).toUTCString()

    if (expire === -1) {

        now = -1

    }

    document.cookie = `${key}=${value};expires=${now};`
}

注意设置过期时间时需要使用toUTCString转换为UTC格式时间,不然设置的是GTM格式的时间(本案例设置过期时间为1小时,为使用toUTCString转换前实际设置的值为9小时)

2. 插件设置(js-cookie)

包下载:npm install js-cookie

包引用:import Cookies from 'js-cookie'

参考文献:https://blog.csdn.net/fay_ren/article/details/121659064

 读取cookie

Cookies.get('name')

 存储cookie

Cookies.set('name', 'value', { expires: 1, path: '/' })

// expires设置为1代表一天后过期,如果想设置一天以内的时间需要在当前时间+失效时间(毫秒)

let nowTimer = new Date().getTime();

let expiresTime = new Date(nowTimer + 60 * 1000 * 60);
 
Cookies.set('name', 'value', { expires: expiresTime});  // 一小时后过期

 删除cookie

Cookies.remove('name')

       

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值