实现效果如下:
html页面
<el-button type="primary" :class="{'disabled-style':getCodeBtnDisable}" :disabled="getCodeBtnDisable" @click="getCode()">{{codeBtnWord}}</el-button>
数据data
data() {
return {
phoneVisibleEdit: false,
editPhone:{
mobile: '',
code: '',
},
phoneRules: {
mobile: [
{required: true, message: '手机号码格式错误', trigger: 'blur', pattern:/^1[3456789]\d{9}$/},
],
code:[
{required: true, message: '请输入验证码', trigger: 'blur' }
]
},
codeBtnWord:'获取验证码',
disabled:false,
waitTime:61,
}
}
通过计算属性computed获取倒计时
computed: {
// 控制获取验证码按钮是否可点击
getCodeBtnDisable:{
get(){
if(this.waitTime == 61){
if(this.editPhone.mobile){
return false
}
return true
}
return true
},
// 注意:因为计算属性本身没有set方法,不支持在方法中进行修改,而要进行这个操作,需要手动添加
set(){}
},
phoneCodeStyle(){
let reg = /^1[3456789]\d{9}$/
if(!reg.test(this.editPhone.mobile)){
return callback(new Error('手机格式不正确'));
} else {
return true;
}
}
},
mothods中添加获取验证码方法
getCode(){
if(this.phoneCodeStyle){
let params = {}
params.phone = this.editPhone.mobile;
// 调用获取短信验证码接口
axios.post('user/sendPhoneMessage', 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)
}
},