vue 发送短信验证码倒计时

<div class="form">
            <button class="send_btn" :class="!login.canGet ? 'btn-disabled' : ''"
              @click="getCode"
              :disabled="!login.canGet"
              type="button">
              <span v-show="!login.canGet">{{login.waitTime+"s"}}后重发</span>
              <span v-show="login.canGet">{{tempLogin.text}}</span>
            </button>
          </div>
data () {
    return {
      tempLogin: { // 定义一个临时对象
        canGet: true,
        timer: null,
        waitTime: 60,
        text: '发送验证码'
      }
    }
  },
computed: {
    login () { // 最终对象
      const _this = this
      if (!this.tempLogin.canGet) {
        if (this.tempLogin.waitTime === 0) {
          _this.tempLogin.text = '重新发送'
        }
        return this.timeCountdown(this.tempLogin)
      } else {
        return this.tempLogin
      }
    },
  },
methods: {
  /* 发送验证码 */
    getCode () {
      // 请求接口开始,成功之后调用
      // 倒计时开始
      this.timeCountdown(this.login) // 参数为最终对象
    },
    timeCountdown (obj) {
      // obj包括timer、waitTime 、canGet
      const TIME_COUNT = 60 // 默认倒计时秒数
      if (!obj.timer) {
        obj.waitTime = TIME_COUNT
        obj.canGet = false
        obj.timer = setInterval(() => {
          if (obj.waitTime > 0 && obj.waitTime <= TIME_COUNT) {
            obj.waitTime--
          } else {
            obj.canGet = true
            clearInterval(obj.timer) // 清空定时器
            obj.timer = null
          }
        }, 1000)
      }
      return {
        timer: obj.timer,
        canGet: obj.canGet,
        waitTime: obj.waitTime
      }
    }  
}
原文地址:https://www.cnblogs.com/adbg/p/14107427.html