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>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM