1. 程式人生 > 實用技巧 >vue 獲取驗證碼倒計時

vue 獲取驗證碼倒計時

html部分

<div class="form-code">
  <input type="number" v-model="codeVer" placeholder="請輸入驗證碼" />
  <button type="button" @click="getCode()" :class="{on:showBtnOn}" v-text="codeText"></button>
</div>
codeText按鈕上顯示的文字;
getCode為按鈕點選事件;
codeVer為驗證碼;
showBtnOn:是否新增button上的class on

css部分,按鈕點選的時候給一個灰色背景:

.form-code button.on{background-color:#999}

在date中定義雙向繫結的部分

data: {
  howBtnOn:false,
  codeVer:'',
  codeText:'獲取驗證碼'
},    

點選方法getCode開始倒計時:

var time = 60;
var timer = setInterval(function(){
  time--;
  vm.codeText = time+"秒重發"
  vm.showBtnOn = true;
  
  //time==0 時,倒計時結束,按鈕切換為原來的顏色,清除定時器
  if(time==0){     clearInterval(timer);     vm.codeText = "獲取驗證碼";     vm.showBtnOn = false;   } },1000);