Vue recently doing a project, through front-end mobile phone number, verification code, access code buttons to set the countdown 60s (after the click, click again in a minute not). Look at renderings:
After entering the phone number in the correct format, "Get Code" button before clicking; click on "Get Code" button to enter the 60s countdown, the effect is as follows:
Renderings already have, then on the code!
- html
<el-button @click="getCode()" :class="{'disabled-style':getCodeBtnDisable}" :disabled="getCodeBtnDisable">{{codeBtnWord}}</el-button>
- Data data
Data () { return { loginForm: { phoneNumber: '', verificationCode: '', }, codeBtnWord: 'Get codes', // get codes button text waitTime: 61, // get codes button failure time } }
- Computed Property 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方法,可以参照(https://www.cnblogs.com/belongs-to-qinghua/p/11936476.html)
- 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) } }
通过上面的代码,就可以实现了,如有错误,敬请指正!