vue獲取手機驗證碼爬坑

貼上代碼:

 <div class="send_code">
     <input placeholder="請輸入驗證碼" v-model="userPwd">
     <button @click="sendCode"  v-show="isShow" style="background-color: red">發送驗證碼</button>
     <button disabled="false" v-show="!isShow" style="background-color: lightgrey">{{secondsCount}}秒後重發</button>
 </div>
  data(){
       return{ 
            userPhone:'',
            secondsCount:0,//倒計秒數初始化定義
            isShow:true  //是否顯示發送驗證碼按鈕
        }
  },
sendCode(){
    if(this.userPhone==''){
         alert("手機號不能爲空");
         return false
    }
    const reg = /^1[3|4|5|7|8][0-9]\d{8}$/;
    if(!reg.test(this.userPhone)){
         alert("請輸入正確的手機號");
         return false
    }else{
         //發送短信驗證
         this.$http.get("/ips/pass/sendSms/"+this.userPhone+".json").then(res=>{
              //倒計時
              let that = this; 
              console.log(that);
              that.secondsCount=60;
              //切換倒計時按鈕
              that.isShow=false;
              //倒計時函數
              let timer=setInterval(function () {
                  console.log(this);
                  that.secondsCount--;
                  if(that.secondsCount<=0){
                       clearInterval(timer);
                       that.isShow=true;
                  }
               },1000)
           })
     }
},

這個地方的一個坑就是  需要將this用that替換一下,如果把代碼改成下面這樣,如果都使用this的話,就如下圖:

這兩個this的指向不同,就會造成this.secondsCount的值在倒計時裏顯示爲NaN,如下圖:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章