uni-app实现获取验证码的倒计时

本文介绍了一种使用三目运算符实现倒计时验证码功能的方法,详细解释了如何通过判断codeTime变量来显示获取验证码按钮的状态,并防止用户在倒计时期间重复点击。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

实现的效果

 

页面部分是一个三目运算,codeTime是倒计时的时间。

<template>
	<view>
		<view class="three">
			<view class="get" @tap="getCheckNum()">
				<text>{{!codeTime?'获取验证码':codeTime+'s'}}</text>
			</view>
			<view class="all">
				<view class="left">验证码</view>
				<input v-model="mydata.checkNum" placeholder="请输入验证码"/>
			</view>
			<button class="btn" @tap='sure'>确认</button>
		</view>
	</view>
</template>

具体思路:

三目运算,判断codeTime的值,当为0的时候显示文字“获取验证码”,大于0的时候显示验证码的倒计时。codeTime默认为0.

这里有个问题就是,怎么阻止用户在倒计时还没结束的时候一直点击,影响倒计时。

解决办法是写个判断,当codeTime大于60的时候,弹窗提示用户不能重复获取验证码。当倒计时运行完了之后要清除倒计时。

代码:

<script>
	export default {
		data() {
			return {
			    codeTime:0,
			}
		},
        methods: {
            getCheckNum(){
				if(this.codeTime>0){
					uni.showToast({
						title: '不能重复获取',
						icon:"none"
					});
				    return;
				}else{
					this.codeTime = 60
					let timer = setInterval(()=>{
						this.codeTime--;
						if(this.codeTime<1){
							clearInterval(timer);
							this.codeTime = 0
						}
					},1000)
                }
           }
     }
}

css样式:

.all{
	margin: 30rpx;
	border-bottom: 2rpx solid #EEEEEE;
	display: flex;
	flex-wrap: nowrap;
}
.left{
	margin-bottom: 30rpx;
	margin-right: 40rpx;
	width: 150rpx;
}
.three{
	background-color: white;
	width: 92%;
	border-radius: 10rpx;
	padding: 20rpx 0;
	margin: 20rpx auto;
	position: relative;
}
.btn{
	background-color: orange;
	font-size: 28rpx;
	width: 160rpx;
	height: 70rpx;
	line-height: 70rpx;
	margin-top: 40rpx;
	color: white;
	font-weight: 600;
}
.get{
	position: absolute;
	top: 40rpx;
	right: 30rpx;
	background-color: orange;
	height: 70rpx;
	line-height: 70rpx;
	color: white;
	border-radius: 10rpx;
	padding: 0 20rpx;
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值