react 封装自己的Cookie库

复制代码
const cookie = {
//根据key值获取对应的cookie getCookie(key: any) {
//获取cookie const data = document.cookie
//获取key第一次出现的位置 let startIndex = data.indexOf(key + '=')
//如果开始索引值大于0表示有cookie if (startIndex > -1) {
//key的起始位置等于出现的位置加key的长度+1 startIndex = startIndex + key.length + 1
//结束位置等于从key开始的位置之后第一次;号所出现的位置 let endIndex = data.indexOf(';', startIndex)
//如果未找到结尾位置则结尾位置等于cookie长度,之后的内容全部获取 endIndex = endIndex < 0 ? data.length : endIndex return decodeURIComponent(data.substring(startIndex, endIndex)) } else { return '' } }, setCookie(key: any, value: any, time?: any) { //默认保存时间 const times = time //获取当前时间 const cur = new Date() /设置指定时间 cur.setTime(cur.getTime() + times * 24 * 3600 * 1000) //创建cookie 并且设置生存周期为UTC时间 document.cookie = key+'=' +encodeURIComponent(value) +';expires=' +(times === undefined ? '' : cur.toUTCString()) }, delCookie(key: any) {
//获取cookie const data = this.getCookie(key)
//如果获取到cookie则重新设置cookie的生存周期为过去时间 if ((data as any) !== false) { this.setCookie(key, data, -1) } } } export default cookie
复制代码

 

posted @   Fly_bokeyuan  阅读(1153)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
点击右上角即可分享
微信分享提示