【uni-app】发送验证码60s倒计时

在这里插入图片描述
在这里插入图片描述
说明:我们做这个倒计时功能可能不会考虑到用户多次重复点击按钮的情况 ,请求响应慢的情况下会导致用户多次点击,造成连续发送多个请求。所以我们可以给定一个变量,默认是可以点击的,点击按钮后,该变量立刻变成false防止再洗点击。当倒计时 结束后该变量再变为true,运行点击。

<view class="item flex align-items-center">
	<view class="title">新手机号</view>
	<view class="newPhone"><input type="text" value="" v-model="newPhone" /></view>
	
	<view class="sendCodeBtn" @click="sendCodeBtn">
		{{send?'发送验证码':second+'s重新发送'}}
	</view>
</view>
data() {
	return {
		s: 60,	//默认倒计时
		second: 0,
		send: true //按钮可以点击
	};
},

methods:{
	// 发送验证码
	sendCodeBtn: function() {
		let that = this;
		// 防止多次重复点击
		if(!that.send){
			return false;
		}
		if (!that.$utils.isMobile(that.newPhone)) {
			uni.showToast({
				title: '请输入正确的手机格式',
				icon: 'none'
			});
			return false;
		}
		
		// 发送验证码
		that.send = false;
		uni.showToast({
			title:'发送成功',
			icon:'none',
			success: () => {
				this.time();	// 倒计时
			}
		})
	},
	// 倒计时
	time(){
		let that = this;
		that.second = that.s;
		let interval = setInterval(function(){
			if(that.second == 1){
				that.send = true;
				that.second = that.s;
				clearInterval(interval);
			}else {
			console.log(that.second)
				that.second--;
			}
		},1000)
	}
}

参考:
uni验证码60秒倒计时


版权声明:本文为cdgogo原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。