鍍金池/ 問答/HTML/ 想用Vue寫個驗證碼倒計時,setInterval()不生效

想用Vue寫個驗證碼倒計時,setInterval()不生效

圖片描述

<div class="verification-code-wrapper">
    <input type="text" placeholder="六位數(shù)字驗證碼" 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()里打印東西正常,但返回值沒效果。

回答
編輯回答
終相守

1 this問題
2 setInterval里面的回調(diào)函數(shù)返回值返回不出去
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);
      }
    }
}
2017年4月25日 14:35
編輯回答
別瞎鬧

回調(diào)里this指向改變。一般的回調(diào)里都是沒返回值的。樓上幾位大大說了解決辦法了我就不貼了

2017年5月10日 22:34
編輯回答
萌小萌

改成這樣

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


this.isCountDown = true
window.setInterval(() => {
            this.time_60 -= 1;
        }, 1000);
2017年9月8日 07:23
編輯回答
久不遇

確實是this指向問題
改成這樣

time_60: 60,


computed: {
    count_down: function () {
        let me = this;
        window.setInterval(function () {
            me.time_60 -= 1;
        }, 1000);
    }
}
2017年12月10日 09:00
編輯回答
神經(jīng)質(zhì)

這和this沒太大關(guān)系,我改了一下

<div class="verification-code-wrapper">
    <input type="text" placeholder="六位數(shù)字驗證碼" 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.

2017年9月21日 21:10