H5W3
当前位置:H5W3 > 其他技术问题 > 正文

想用Vue写个验证码倒计时,setInterval()不生效

图片描述

<div class="verification-code-wrapper">
    <input type="text" placeholder="六位数字验证码" ref="phone_login_verification_code">
    <a class="get-code"
       @click="get_verification_code(phone_login, type=3)">获取验证码</a>

    <div class="count-down" v-show="count_down">{{count_down}}秒后重新获取</div>
</div>

time_60: 60,


computed: {
    count_down: function () {

        window.setInterval(function () {
            this.time_60 -= 1;
            return this.time_60;
        }, 1000);
    }
}

setInterval()里打印东西正常,但返回值没效果。

回答:

改成这样

<div class="count-down" v-show="isCountDown">{{time_60}}秒后重新获取</div>
isCountDown: false


this.isCountDown = true
window.setInterval(() => {
            this.time_60 -= 1;
        }, 1000);

回答:

1 this问题
2 setInterval里面的回调函数返回值返回不出去
3 用computed不太合理

time_60:60,
count_down:true

methods:{
    startCountdown:function(){
      if(count_down){
        count_down = false;
        var timer = window.setInterval(()=>{
          this.time_60 -= 1;
          if(this.time_60<=0){
              this.time_60 = 60;
              count_down = true;
              window.clearInterval(timer)
          }
        }, 1000);
      }
    }
}

回答:

确实是this指向问题
改成这样

time_60: 60,


computed: {
    count_down: function () {
        let me = this;
        window.setInterval(function () {
            me.time_60 -= 1;
        }, 1000);
    }
}

回答:

这和this没太大关系,我改了一下

<div class="verification-code-wrapper">
    <input type="text" placeholder="六位数字验证码" ref="phone_login_verification_code">
    <a class="get-code"
       @click="get_verification_code(phone_login, type=3)">获取验证码</a>

    <div class="count-down" v-show="time_60 > 0" >{{time_60}}{{count_down}}秒后重新获取</div>
</div>
count_down: function () {
    window.setInterval(() => {
        this.time_60 -= 1;
    }, 1000);
}

it has worked.

回答:

回调里this指向改变。一般的回调里都是没返回值的。楼上几位大大说了解决办法了我就不贴了

本文地址:H5W3 » 想用Vue写个验证码倒计时,setInterval()不生效

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址