Vue项目实现记住密码到cookie功能

效果如果所示:


image.png

思路:勾选记住密码框,点击登录,账号密码勾选状态保存到cookie,下次登录将账号密码勾选状态从cookie中取出;不勾选时,点击登录清空保存到cookie的值

代码如下:

HTML部分


JS部分

  data() {
    return {
      username: "",
      password: "",
      checked:false
    };
  },
  mounted() {
    this.getCookie();
  },
methods: {
    // 登录
    loadData() {
          if (Boolean(this.checked) == true) {
            console.log(this.checked);
            // 将账号密码勾选状态存入cookie中,并设置储存天数
            this.setCookie(this.username, this.password,this.checked, 7);
          } else {
            //  清除cookie值
            this.clearCookie();
          }
    },
    //设置cookie
    setCookie(c_name, c_pwd,c_che, exdays) {

      var exdate = new Date(); //获取时间
      exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * exdays); //保存的天数
      //字符串拼接cookie
      window.document.cookie =
        "userName" + "=" + c_name + ";path=/;expires=" + exdate.toGMTString();
      window.document.cookie =
        "userPwd" + "=" + c_pwd + ";path=/;expires=" + exdate.toGMTString();

         window.document.cookie =
        "userChe" + "=" + c_che+ ";path=/;expires=" + exdate.toGMTString();
    },

    //读取cookie
    getCookie: function () {
      if (document.cookie.length > 0) {
        var arr = document.cookie.split("; "); //这里显示的格式需要切割一下自己可输出看下
        for (var i = 0; i < arr.length; i++) {
          var arr2 = arr[i].split("="); //再次切割
          //判断查找相对应的值
          console.log(arr2);
          if (arr2[0] == "userName") {
            this.username = arr2[1]; //保存到保存数据的地方
          } else if (arr2[0] == "userPwd") {
            this.password = arr2[1];
          }else if(arr2[0]=="userChe") {
            if(arr2[1]==-1){
              this.checked=false
            }else {
              this.checked=arr2[1];
            }
          }
        }
      }
    },
    //清除cookie
    clearCookie: function () {
      this.setCookie("", "","", -1); //修改2值都为空,天数为-1就好了
    },
  },

你可能感兴趣的:(Vue项目实现记住密码到cookie功能)