×

聊聊在Vue开发中操作cookie的一些应用

作者:Terry2022.10.26来源:Web前端之家浏览:2581评论:1
关键词:vuejs

在Vue项目开发中,操作cookie经常会应用到,今天我们学下基本操作:设置cookie、删除cookie、获取cookie。

1、设置cookie:

cookie.set (key, value, attributes)

比如cookie.set(‘userId’, ‘jack’)。

来个例子:

Vue.prototype.Setcookie = function (name,value) {
  //设置名称为name,值为value的Cookie
  var expdate = new Date();   //初始化时间
  expdate.setTime(expdate.getTime() + 30 * 60 * 1000);   //时间单位毫秒
  document.cookie = name + "=" + escape(value) + ";expires=" + expdate.toGMTString() + ";path=/";
  //即document.cookie= name+"="+value+";path=/";  时间默认为当前会话可以不要,但路径要填写,因为JS的默认路径是当前页,如果不填,此cookie只在当前页面生效!
}

2、获取cookie:

cookie.get (key, json)

比如 cookie.get (‘userId’)

来个例子:

Vue.prototype.getcookie = function (a){
  // console.log(a)
  var d;
  var b = document.cookie;
  // console.log(b)
  var c = b.split(";");
  for (let e = 0; e < c.length; e++) {
    var f = c[e].split("=");
    if (a == f[0].toString().trim()) {
      d = f[1];
      break;
    }
  } if (void 0 == d || null == d) {
    return "";
  }
  else {
    var g = unescape(d.trim());
    return g;
  }
}

3、删除cookie

cookie.remove(key, attributes)

比如 cookie.remove(‘userId’) 移除userId的cookie。

来给例子:

Vue.prototype.delCookie= function (a){
      var b = new Date(0).toGMTString();
      document.cookie = a + "=;expires=" + b + ";path=/";
},

4、Vue允许跨域携带cookie

import axios from 'axios'
axios.defaults.withCredentials = true;// 允许跨域携带cookie

或者在请求拦截器中添加:

config.headers['Access-Control-Allow-Credentials']=true

您的支持是我们创作的动力!
温馨提示:本文作者系Terry ,经Web前端之家编辑修改或补充,转载请注明出处和本文链接:
https://www.jiangweishan.com/article/vuejs20221026.html

网友评论文明上网理性发言 已有1人参与

发表评论:

评论列表