简单的 存取删读cookie

两种方式 存取删读cookie

第一种
//存cookies
例如:this.setCookie(‘authorization’, JSON.stringify({authorization: res.data.content}), 1)

//第一个参数是 cookie名字 第二个是cookie的值 第三个就是cookie存在的时间

Vue.prototype.setCookie = function (name, value, day) {
  if (day) { //如果当前给cookie设置了时间
    var exp = new Date();
    exp.setTime(exp.getTime() + day * 24 * 60 * 60 * 1000);
    document.cookie = name + "=" + escape(value) + ";path=/;expires=" + exp.toGMTString();
  }
  else {
    document.cookie = name + "=" + escape(value) + ';path=/';
  }
}

// 取cookies

Vue.prototype.getCookie = function (name) {
  var arr,
    reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
  if ((arr = document.cookie.match(reg))) return unescape(arr[2]);
  else return null;
}

// 删除cookies

Vue.prototype.delCookie = function (name) {
  var exp = new Date();
  exp.setTime(exp.getTime() - 1000);
  var cval = this.getCookie(name);
  if (cval != null)
    document.cookie = name + "=" + cval + ";path=/;expires=" + exp.toGMTString();
}

//读cookies 登录验证的时候需要获取的cookie

Vue.prototype.getAuthorization = function () {
    if(this.getCookie('authorization')){
        return JSON.parse(this.getCookie('authorization')).authorization
    }else {
        this.$router.push({ path: '/Login' });
        return;
  }

第二种
//第一个参数是 cookie名字 第二个是cookie的值 第三个就是cookie存在的时间

Vue.prototype.setCookie = function (key, value, days) {
  // 设置过期原则
  if (!value) {
    localStorage.removeItem(key)
  } else {
    var Days = days || 1; // 默认保留1天
    var exp = new Date();
    localStorage[key] = JSON.stringify({
      value,
      expires: exp.getTime() + Days * 24 * 60 * 60 * 1000
    })
  }
}

//读取cookies

Vue.prototype.getCookie = function (name) {
  try {
    let o = JSON.parse(localStorage[name])
    if (!o || o.expires < Date.now()) {
      return null
    } else {
      return o.value
    }
  } catch (e) {
      // 兼容其他localstorage 
    // console.log(e)
    return localStorage[name]
  } finally {
  }
}

//删除cookies

Vue.prototype.delCookie = function (key) {
  localStorage.removeItem(key)
}

// 读token

Vue.prototype.getToken = function () {
  var that = this;
  var authorization
  if(this.getCookie('gateway_token')){
     authorization = this.getCookie('gateway_token');
  }else{
    authorization = null
  };

//如果token失效重新获取

 if (authorization == null) {
    $.ajax({
      url: that.GLOBAL.url + "auth/token?username=jingzhun&password=360fob",
      type: "GET",
      async: false,
      success: function (data) {
        if (data.status == 1 && data.message == 'SUCCESS') {
          authorization = "Bearer " + data.content;
          //保存6小时
          that.setCookie('gateway_token', authorization, 1);
        } else {
          that.$message({
            message: that.$t('messages.getTokenFailed'),
            type: "error",
            customClass: "base-message-zindex"
          });
        }
      },
      error: function () {
        that.$message({
          message: that.$t('messages.erverException'),
          type: "error",
          customClass: "base-message-zindex"
        });
      }
    });
  }
  return authorization;
}

个人建议第一种方法,但是前提是你登录的接口不需要cookie验证只需要账号密码 而cookie是在登录成功的时候 接口返回的

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值