Vue 验证码倒计时实现(刷新保持状态)

Vue 验证码倒计时实现(刷新保持状态)
Vue 验证码倒计时实现(刷新保持状态)

mConfigs.ver_code_ide 这个为倒计时写入stora的key唯一名称,为了避免系统内,多处倒计时,key不是唯一问题

大家参考倒计时逻辑即可,每个人的项目不同,这里提供大概的实现代码

export default {
  name: "bm_phone_login",
  data () {
    return {
      //用户输入信息
      input_info: {
        phone: "",
        code: "",
      },
      //倒计时
      countDownTime: 60,
      timeOut: true,
      timer: null,
      //错误信息
      errorFlag: {
        phone_empty: false,
        phone_err: false,
        code_empty: false,
        code_err: false
      },
      //登录按钮禁用
      isLoginForbidden: true,
      // 获取验证码按钮禁用
      getCodeDisabled: true,
      // 获取验证码按钮文字
      getCodeBtnText: "获取验证码",

      countdownIng: false,
    }
  },
  mounted () {
    let sendEndTime = localStorage.getItem(`startTime${this.mConfigs.ver_code_ide}`);
    if (sendEndTime) {
      this.countdown();
    }
  },

  methods: {
    /**************************************************************获取验证码**************************************************************/
    countdown () {
      let that = this;

      let startTime = localStorage.getItem(`startTime${that.mConfigs.ver_code_ide}`);
      let nowTime = new Date().getTime();
      if (startTime) {
        let surplus = 60 - parseInt((nowTime - startTime) / 1000, 10);
        this.countDownTime = surplus <= 0 ? 0 : surplus;
      } else {
        this.countDownTime = 60;
        localStorage.setItem(`startTime${this.mConfigs.ver_code_ide}`, nowTime);
      }

      that.timer = setInterval(() => {
        that.countDownTime--;
        that.getCodeBtnText = that.countDownTime + "秒";
        that.getCodeDisabled = true;
        that.countdownIng = true;
        if (that.countDownTime <= 0) {
          localStorage.removeItem(`startTime${this.mConfigs.ver_code_ide}`);
          clearInterval(that.timer);
          that.countDownTime = 60;
          that.timeOut = true;
          that.countdownIng = false;
          if (that.input_info.phone == "") {
            that.getCodeDisabled = true;
          } else {
            that.getCodeDisabled = false;
          }
          that.getCodeBtnText = "获取验证码";
        }
      }, 1000)
    },
    getVerifyCode () {
      let that = this;
      let input_phone = this.input_info.phone.replace(/\s*/g, "");      //去除空格
      this.$emit('parent_get_code', input_phone, function (flag) {
        if (flag) {
          //倒计时
          if (!that.errorFlag.phone_err && !that.errorFlag.phone_empty) {
            // Toast('验证码已发送');
            that.countdown();
          } else {
            that.errorFlag.phone_empty = true;
          }
        } else {
          that.timeOut = true;
        }
      });
      this.timeOut = false;

   }
}
</script>
上一篇:位运算学习(一)--加 “两道只出现一次的数字”的习题


下一篇:element-ui 日期选择器 限制结束时间不能大于开始时间