【记录】Vue 登录记住用户名密码

template

记住密码

data

data(){
    return{
        userName:'',
        passWord:'',
        checked:false,
    }
},

watch

checked(val){
  val ? this.setCookie() : this.clearCookie();
}

mounted

this.getCookie();

methods

/*
  设置cookie  
  参数:用户名-密码-到期天数
*/
setCookie(username=this.userName, password=this.passWord, num=7) {
  const time = new Date();
  time.setTime(time.getTime() + (24 * 60 * 60 * 1000 * num));
  //window.btoa对用户名和密码编码,不让cookie明文展示
  window.document.cookie = `userName=${window.btoa(username)}; path=/; expires=${time.toGMTString()}`;
  window.document.cookie = `passWord=${window.btoa(password)}; path=/; expires=${time.toGMTString()}`;
  window.document.cookie = `checked=${true}; path=/; expires=${time.toGMTString()}`;
},

 /* 读取cookie */
getCookie() {
  const { cookie } = document;
  if (cookie.length > 0) {
    const cookieNo = cookie.split(";");
    for (const i in cookieNo) {
      const cookieYes = cookieNo[i].split("=");
      //消除文本空格
      cookieYes.forEach((item,index)=>cookieYes[index]=item.replace(/\s+/g,''));
      switch(cookieYes[0]){
        case 'userName':
          this.userName = window.atob(cookieYes[1]);
          break;
        case 'passWord':
          this.passWord = window.atob(cookieYes[1]);
          break;
        case 'checked':
          this.checked = JSON.parse(cookieYes[1]);
          break;
      }
    }
  }
},

/* 清除cookie */
clearCookie() {
  this.setCookie("", "", -1);
},

你可能感兴趣的:(【记录】Vue 登录记住用户名密码)