1. 程式人生 > 程式設計 >Vue實現手機號、驗證碼登入(60s禁用倒計時)

Vue實現手機號、驗證碼登入(60s禁用倒計時)

最近在做一個Vue專案,前端通過手機號、驗證碼登入,獲取驗證碼按鈕需要設定60s倒計時(點選一次後,一分鐘內不得再次點選)。先看一下效果圖:

Vue實現手機號、驗證碼登入(60s禁用倒計時)

輸入正確格式的手機號碼後,“獲取驗證碼”按鈕方可點選;點選“獲取驗證碼”後,按鈕進入60s倒計時,效果圖如下:

Vue實現手機號、驗證碼登入(60s禁用倒計時)

Vue實現手機號、驗證碼登入(60s禁用倒計時)

 效果圖已經有了,接下來就上程式碼吧!

  • html
<el-button @click="getCode()" :class="{'disabled-style':getCodeBtnDisable}" :disabled="getCodeBtnDisable">{{codeBtnWord}}</el-button>
  • 資料data
data() {
return {
loginForm: {
phoneNumber: '',verificationCode: '',},codeBtnWord: '獲取驗證碼',// 獲取驗證碼按鈕文字
waitTime:61,// 獲取驗證碼按鈕失效時間
}
}
  • 計算屬性computed
computed: {
// 用於校驗手機號碼格式是否正確
phoneNumberStyle(){
let reg = /^1[3456789]\d{9}$/
if(!reg.test(this.loginForm.phoneNumber)){
return false
}
return true
},// 控制獲取驗證碼按鈕是否可點選
getCodeBtnDisable:{
get(){
if(this.waitTime == 61){
if(this.loginForm.phoneNumber){
return false
}
return true
}
return true
},// 注意:因為計算屬性本身沒有set方法,不支援在方法中進行修改,而下面我要進行這個操作,所以需要手動新增
set(){}
}
}

關於上面給計算屬性新增set方法,可以參照//www.jb51.net/article/202496.htm

  • css設定不可點選時置灰
.el-button.disabled-style {
background-color: #EEEEEE;
color: #CCCCCC;
}
  • mothods中新增獲取驗證碼方法
getCode(){
if(this.phoneNumberStyle){
let params = {}
params.phone = this.loginForm.phoneNumber
// 呼叫獲取簡訊驗證碼介面
axios.post('/sendMessage',params).then(res=>{
res = res.data
if(res.status==200) {
this.$message({
message: '驗證碼已傳送,請稍候...',type: 'success',center:true
})
}
})
// 因為下面用到了定時器,需要儲存this指向
let that = this
that.waitTime--
that.getCodeBtnDisable = true
this.codeBtnWord = `${this.waitTime}s 後重新獲取`
let timer = setInterval(function(){
if(that.waitTime>1){
that.waitTime--
that.codeBtnWord = `${that.waitTime}s 後重新獲取`
}else{
clearInterval(timer)
that.codeBtnWord = '獲取驗證碼'
that.getCodeBtnDisable = false
that.waitTime = 61
}
},1000)
}
}

通過上面的程式碼,就可以實現了,如有錯誤,敬請指正!

以上就是Vue實現手機號、驗證碼登入(60s禁用倒計時)的詳細內容,更多關於vue 手機號驗證碼登入的資料請關注我們其它相關文章!