Vue设置cookie,cookie的存储、获取、清除

// 设置cookie

/**
 *
 * @param {*} exdays  保存天数
 * 使用
 *   文件目录
 *     总目录
 *       - src
 *         - utils
 *          - cookie.js
 * 
 *   单文件引入使用
 *   import { setCookie, getCookie, clearCookie, clearCookies } from '@/utils/cookie'
 *    
 * setCookie(参数名(),参数值, 保存天数)  存储cookie
 * getCookie(参数名)                    获取cookie
 * clearCookie(参数名)                  清除cookie
 * clearCookies()                       清除所有cookie
 *
 */

function setCookie(cName = '', cValue = '', exdays = '') {
  var exdate = new Date() // 获取时间
  exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * exdays) // 保存的天数
  // 字符串拼接cookie
  window.document.cookie = cName + '=' + escape(JSON.stringify(cValue)) + ';path=/;expires=' + exdate.toGMTString()
}

// 读取cookie
function getCookie(name) {
  if (document.cookie.length > 0) {
    var allcookies = document.cookie
    name += '='
    var pos = allcookies.indexOf(name)
    if (pos != -1) {
      var start = pos + name.length
      var end = allcookies.indexOf(';', start)
      //这里根据','分隔出该名称的值,如果设置Cookie时用的是','分隔请替换成相应符号。
      if (end == -1) {
        end = allcookies.length
      }
      var value = allcookies.substring(start, end)
      return JSON.parse(unescape(value))
    } else {
      return
    }
  }
}

// 清除cookie
function clearCookie(name) {
  setCookie(name, '', -1) // 修改2值都为空,天数为负1天就好了
}

// 清除所有cookie
function clearCookies() {
  var temp = document.cookie.split(';')
  var name
  for (var i = 0; ; i++) {
    if (!temp[i]) break
    name = temp[i].split('=')[0]
    var exp = new Date()
    exp.setTime(exp.getTime() - 1)
    document.cookie = name + "= ''" + '; expires=' + exp.toGMTString()
  }
}
export { setCookie, getCookie, clearCookie, clearCookies }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值