登陆 记住密码

登陆 记住密码_第1张图片

方式一 localStorage

安装 npm install --save js-base64
使用 import { Base64 } from ‘js-base64’;

private mounted() {
    if(getStorage('userPassword')){
      this.model = {
        user_name: getStorage('userName') as string,
        password: Base64.decode(getStorage('userPassword') as string)
      }

      this.rememberPwd=true; 
    }
  }

  private async login () {
    const form = this.$refs.form as Form;
    if (!(await form.validate())) {
      return;
    }
    await this.$store.dispatch('auth/login', this.model).then(() => {
      if (this.rememberPwd) {
        let password = Base64.encode(this.model.password); // base64加密
        localStorage.setItem("userName", this.model.user_name);
        localStorage.setItem("userPassword", password);
      } else {
        localStorage.removeItem("userName");
        localStorage.removeItem("userPassword");
      }
      document.location.href = '/';
    }).catch((e) => {
      this.$message.error('登录失败');
    });
  }

方式二 cookies


private mounted() {
    this.getCookie();
  }

  private async login () {
    const form = this.$refs.form as Form;
    if (!(await form.validate())) {
      return;
    }
    await this.$store.dispatch('auth/login', this.model).then(() => {
      if (this.rememberPwd) {
        let password = Base64.encode(this.model.password); // base64加密
        this.setCookie(this.model.user_name, password, 7);
      }else{
        this.setCookie("", "", -1); // 修改2值都为空,天数为负1天就好了
      }

      document.location.href = '/';
    }).catch((e) => {
      this.$message.error('登录失败');
    });
  }

 private setCookie(userName, password, days) {
    let date = new Date(); // 获取时间
    date.setTime(date.getTime() + 24 * 60 * 60 * 1000 * days); // 保存的天数
    // 字符串拼接cookie
    window.document.cookie =
      "userName" + "=" + userName + ";path=/;expires=" + date.toUTCString();
    window.document.cookie =
      "userPassword" + "=" + password + ";path=/;expires=" + date.toUTCString();
  }

  // 读取cookie 将用户名和密码回显到input框中
  private getCookie() {
    if (document.cookie.length > 0) {
      let arr = document.cookie.split("; "); //分割成一个个独立的“key=value”的形式
      console.log("arr",arr) // ['userName=adminior', 'userPassword=aHNyYWRtdd4yMDIw']
      for (let i = 0; i < arr.length; i++) {
        let arr2 = arr[i].split("="); // 再次切割,arr2[0]为key值,arr2[1]为对应的value
        if (arr2[0] === "userName") {
          this.model.user_name = arr2[1];
        } else if (arr2[0] === "userPassword") {
          this.model.password = Base64.decode(arr2[1]);// base64解密
          this.rememberPwd = true;
        }
      }
    }
  }

你可能感兴趣的:(vue)