基于vue2完成一个短信验证码倒计时60s的功能

1.结构(结构和css样式可根据自己需要修改)

<input type="number" name="code" maxlength="6" placeholder="请输入验证码" v-model="user.code" />
<button :disabled="disabled" class="t-c" @tap="getCode()">{{title}}</button>

2.js部分

export default {
		data() {
			return {
				second: '', //倒计时
				disabled: false, //是否禁用按钮
				timer: null, //计时器
				user: {
					oldPassword: '', //旧密码
					password: '', //密码
					password2: '', //密码
					userName: '', //个人姓名
					phone: '', //手机号码
					certificationId: '', //身份证号
					code: '' //验证码
				}
			};
		},
            //计算属性
		computed: {
			title() {
				return this.disabled ? `重新获取 ( ${this.second} ) s` : '获取验证码';
			},
		},
		methods: {
			//获取短信验证码
			getCode() {
				console.log('点击')
				let that = this
				let s = 60  //倒计时间
				if (!that.timer) {
					that.second = s
					that.disabled = true
					that.timer = setInterval(() => {
						if (that.second > 0 && this.second <= s) {
							that.second--
						} else {
							that.disabled = false
							clearInterval(that.timer)
							this.timer = null
						}
					}, 1000)
				}
			},
	};
  • 不建议使用全局定时器,容易出现内存泄漏等问题。
  • 推荐使用Vue的watchcomputed等响应式数据实现倒计时功能。
  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值