Vue

vue实现登录记住密码和登录验证码

2022-06-09  本文已影响0人  爱学习的小仙女早睡早起

用到的依赖 js-base64、js-cookie

实现:利用js-base64将密码加密;利用js-cookie将账号与密码存到cookie;

main.js
let Base64 = require("js-base64").Base64;
Vue.prototype.$Base64 = Base64;
login.vue
 <el-checkbox class="remember" v-model="rememberPSW">记住密码</el-checkbox>
js
import Cookies from "js-cookie";

created() {
    this.$nextTick(() => {
      this.$refs.userName.focus();
    });

    this.getCookie()  // 读取记住的账号密码信息
},

methods:{
    // 获取cookie保存的登录信息
    getCookie() {
      const username = Cookies.get("username");
      const password = Cookies.get("password");
      const rememberPSW = Cookies.get('rememberPSW')
      this.userName = username === undefined ? this.userName : username,
      this.userPassword = password === undefined ? this.userPassword : this.$Base64.decode(password),
      this.rememberPSW = rememberPSW === undefined ? false : Boolean(rememberPSW)
      if(this.rememberPSW){
        this.$nextTick(()=> {
          this.$refs.smsCode.focus();
        })
      }
    },

}


// 登录野口调用成功后的then函数里
          if (this.rememberPSW) {
            Cookies.set("username", this.userName, { expires: 30 });
            Cookies.set("password", this.$Base64.encode(this.userPassword), { expires: 30 });
            Cookies.set('rememberPSW', this.rememberPSW, { expires: 30 });
          } else {
            Cookies.remove("username");
            Cookies.remove("password");
            Cookies.remove('rememberPSW');
          }


登录验证码

login.vue
 <el-input v-model="smsCode" @keyup.enter.native="ToLogin()" maxlength="6" ref="smsCode" placeholder="请输入验证码">
          <i slot="prefix" class="iconfont iconyanzhengma"></i>
          <el-button :disabled="!!timer" slot="append" class="text-color" @click="getSMSCode">
            {{ !timer ? "获取验证码" : times + "s后获取" }}
          </el-button>
        </el-input>

js
// 获取短信验证码
    getSMSCode() {
      if (!this.userName) {
        this.$message.error("请先输入账号");
        this.$refs.userName.focus();
        return;
      }
      API_User.sendCodeByAccount({
        account: this.userName,
      }).then((res) => {
        this.$message.success("短信验证码发送成功");
        this.sendCode();
      });
    },


    sendCode() {
      this.timer = setInterval(() => {
        if (this.times === 0) {
          clearInterval(this.timer);
          this.timer = null;
          this.times = 60;
        } else {
          this.times -= 1;
        }
      }, 1000);
    },
上一篇 下一篇

猜你喜欢

热点阅读