写法1:

methods: {
  //设置cookie
      setCookie: function (cname, cvalue, exdays) {
        var d = new Date();
        d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
        var expires = “expires=” + d.toUTCString();
        console.info(cname + “=” + cvalue + "; " + expires);
        document.cookie = cname + “=” + cvalue + "; " + expires;
        console.info(document.cookie);
      },
      //获取cookie
      getCookie: function (cname) {
        var name = cname + “=”;
        var ca = document.cookie.split(’;’);
        console.log(“获取cookie,现在循环”)
        for (var i = 0; i < ca.length; i++) {
          var c = ca[i];
          console.log©
          while (c.charAt(0) == ’ ') c = c.substring(1);
          if (c.indexOf(name) != -1){
            return c.substring(name.length, c.length);
          }
        }
        return “”;
      },
      //清除cookie
      clearCookie: function () {
        this.setCookie(“username”, “”, -1);
      },
      checkCookie: function () {
        var user = this.getCookie(“username”);
        if (user != “”) {
          alert("Welcome again " + user);
        } else {
          user = prompt(“Please enter your name:”, “”);
          if (user != “” && user != null) {
            this.setCookie(“username”, user, 365);
          }
        }
      }
    },
    created() {
      scroll(0, 0);
      this.checkCookie();
    }

写法2:

//设置cookie

/**

* 设置cookie

* name cookie的名称

* value cookie的值

* day cookie的过期时间

*/

Vue.prototype.setCookie = function (name, value, day) {

if (day !== 0) { //当设置的时间等于0时,不设置expires属性,cookie在浏览器关闭后删除

var curDate = new Date();

var curTamp = curDate.getTime();

var curWeeHours = new Date(curDate.toLocaleDateString()).getTime() - 1;

var passedTamp = curTamp - curWeeHours;

var leftTamp = 24 * 60 * 60 * 1000 - passedTamp;

var leftTime = new Date();

leftTime.setTime(leftTamp + curTamp);

document.cookie = name + “=” + escape(value) + “;expires=” + leftTime.toGMTString();

} else {

document.cookie = name + “=” + escape(value);

}

}

Vue.prototype.getCookie = function (name) {

var arr;

var reg = new RegExp("(^| )" + name + “=([^;]*)(;|$)”);

if (arr = document.cookie.match(reg))

return unescape(arr[2]);

else

return null; ocument.cookie = name + “=” + escape(value);

}

//在页面中获取cookie  let showcookie = this.getCookie(‘wxshowstated’);

//在页面中设置cookie  this.setCookie(‘wxshowstated’, ‘1’, 360);

作者:零零零jiawei
来源:CSDN
原文:https://blog.csdn.net/ljw_jiawei/article/details/80605911
版权声明:本文为博主原创文章,转载请附上博文链接!

Logo

前往低代码交流专区

更多推荐