Vue修改手机号(获取验证码按钮60秒倒计时禁用)

实现效果如下:
在这里插入图片描述
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)
						}
				},
  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值