【uni-app】实现获取验证码功能

 【uni-app】实现获取验证码功能

一、注册界面-获取验证码的需求:

情况1:手机号码正确
输入手机号码---点击--“获取验证码”---出现“发送中”...---重新获取(60)


 

 

 

 情况2:手机号码不正确
输入手机号码(或没有输入)---点击获取验证码--弹出“请输入“ 正确号码的手机号码 ”的提示框

 

 

 二、思路如下:
(1)先进行排版,设置输入框input的参数,初始值

(2)绑定点击事件,追加样式 
(3)在点击事件里面

第一步:

需要判断手机号码的正确与否,校验手机号码是否有误

第二步:

调用setTimeout定时器方法,

同时需要设置每隔60秒就重新获取验证码,就需要调用SetTimer函数

第三步:

同时需要setInterval方法,不停地调用函数,

直到 clearInterval被调用或窗口被关闭,且需要隐藏软键盘及颜色的切换

 

 

源码如下(里面包含注册界面的全部内容):

<template>
	
	
	<view>
		<!-- 登录页面正中间图标 -->
		<view class="logo">
			<view class="img">
				<image mode="widthFix"
					src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fup.enterdesk.com%2Fedpic%2Fd0%2Fa5%2F86%2Fd0a586e0cece1f1dec648e9aa3d8c9d6.jpg&refer=http%3A%2F%2Fup.enterdesk.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1633761077&t=84f5ce7dc4918ef2e89d1fa4e1e72504">
				</image>
			</view>
		</view>
		<!-- 注册界面 -->
		<view class="form userform">
			<view class="username">
				<view class="get-code" :style="{'color':getCodeBtnColor}" @click.stop="getCode()">{{getCodeText}}</view>
				<input placeholder="请输入手机号" v-model="phoneNumber" placeholder-style="color: rgba(255,255,255,0.8);" />
			</view>
			<view class="code">
				<input placeholder="请输入验证码" v-model="code" placeholder-style="color: rgba(255,255,255,0.8);" />
			</view>
			<view class="password">
				<input placeholder="请输入密码" v-model="passwd" password=true
					placeholder-style="color: rgba(255,255,255,0.8);" />
			</view>
			<view class="btn" @tap="doReg">立即注册</view>
			<view class="res">
				<view @tap="toLogin">已有账号立即登录</view>
			</view>
		</view>

	</view>
</template>

<script>
	import md5 from "@/common/SDK/md5.min.js";
	export default {
		data() {
			return {
				phoneNumber: "",
				code: '',
				passwd: "",
				getCodeText: '获取验证码',
				getCodeBtnColor: "#ffffff",
				getCodeisWaiting: false
			}
		},
		onLoad() {

		},
		methods: {
			Timer() {},
			getCode() {
				uni.hideKeyboard() //隐藏已经显示的软键盘,如果软键盘没有显示则不做任何操作。
				if (this.getCodeisWaiting) {
					return;
				}
				if (!(/^1(3|4|5|6|7|8|9)\d{9}$/.test(this.phoneNumber))) { //校验手机号码是否有误
					uni.showToast({
						title: '请填写正确手机号码',
						icon: "none"
					});
					return false;
				}
				this.getCodeText = "发送中..." //发送验证码
				this.getCodeisWaiting = true;
				this.getCodeBtnColor = "rgba(255,255,255,0.5)" //追加样式,修改颜色
				//示例用定时器模拟请求效果
				//setTimeout(()用于在指定的毫秒数后调用函数或计算表达式
				setTimeout(() => {
					uni.showToast({
						title: '验证码已发送',
						icon: "none"
					}); //弹出提示框
					//示例默认1234,生产中请删除这一句。
					this.code = '1234'; //发送验证码,进行填入
					this.setTimer(); //调用定时器方法
				}, 1000)
			},
			//setTimer: 需要每隔一段时间执行一件事的的时候就需要使用SetTimer函数
			setTimer() {
				let holdTime = 60; //定义变量并赋值
				this.getCodeText = "重新获取(60)"
				//setInterval()是一个实现定时调用的函数,可按照指定的周期(以毫秒计)来调用函数或计算表达式。
				//setInterval方法会不停地调用函数,直到 clearInterval被调用或窗口被关闭。
				this.Timer = setInterval(() => {
					if (holdTime <= 0) {
						this.getCodeisWaiting = false;
						this.getCodeBtnColor = "#ffffff";
						this.getCodeText = "获取验证码"
						clearInterval(this.Timer); //清除该函数
						return; //返回前面
					}
					this.getCodeText = "重新获取(" + holdTime + ")"
					holdTime--;
				}, 1000)
			},
			doReg() {
				uni.hideKeyboard() //隐藏已经显示的软键盘,如果软键盘没有显示则不做任何操作。
				//模板示例部分验证规则
				if (!(/^1(3|4|5|6|7|8|9)\d{9}$/.test(this.phoneNumber))) { //校验手机号码
					uni.showToast({
						title: '请填写正确手机号码',
						icon: "none"
					});
					return false;
				}
				//示例验证码,实际使用中应为请求服务器比对验证码是否正确。
				if (this.code != 1234) {
					uni.showToast({
						title: '验证码不正确',
						icon: "none"
					});
					return false;
				}
				uni.showLoading({
					title: '提交中...'
				})
				//模板示例把用户注册信息储存在本地,实际使用中请替换为上传服务器。
				setTimeout(() => {
					uni.getStorage({
						key: 'UserList',
						success: (res) => {
							//增加记录,密码md5
							res.data.push({
								username: this.phoneNumber,
								passwd: md5(this.passwd)
							})
							uni.setStorage({
								key: 'UserList',
								data: res.data,
								success: function() {
									uni.hideLoading()
									uni.showToast({
										title: '注册成功',
										icon: "success"
									});
									setTimeout(function() {
										uni.navigateBack();
									}, 1000)
								}
							});
						},
						fail: (e) => {
							uni.hideLoading()
							console.log('error');
							//新建UserList
							uni.setStorage({
								key: 'UserList',
								data: [{
									username: this.phoneNumber,
									passwd: md5(this.passwd)
								}],
								success: function() {
									uni.hideLoading()
									uni.showToast({
										title: '注册成功',
										icon: "success"
									});
									setTimeout(function() {
										uni.navigateBack();
									}, 1000)
								},
								fail: function(e) {
									console.log('set error:' + JSON.stringify(e));
								}
							});
						}
					});
				}, 1000)
			},
			toLogin() {
				uni.hideKeyboard() //隐藏已经显示的软键盘,如果软键盘没有显示则不做任何操作。
				uni.redirectTo({
					url: 'login'
				}); //跳转到登录页
				uni.navigateBack(); //关闭当前页面,返回上一页面
			}
		}
	}
</script>

<style lang="scss">
	

	page {
		background: #3F536E; //整一个页面的背景颜色
		// linear-gradient(to bottom, #f06c7a 0%, #f06c7a 100%);
		height: 100%;
	}

	.icon {
		color: #ffffff;
	}

	.logo {
		width: 100%;
		height: 45vw;
		display: flex;
		justify-content: center;
		align-items: center;

		.img {
			width: 25%;
			height: 25vw;

			image {
				width: 100%;
				border-radius: 100%;
			}
		}
	}

	.form {
		width: 86%;
		padding: 0 7%;
		font-size: 30upx;

		.username,
		.password,
		.code {
			width: calc(100% - 90upx);
			height: 90upx;
			display: flex;
			align-items: center;
			border-radius: 45upx;
			background-color: rgba($color: #ffffff, $alpha: 0.1);
			padding: 0 45upx;
			margin-bottom: 26upx;

			input {
				width: 100%;
				height: 50upx;
				color: rgba($color: #ffffff, $alpha: 0.8);
				font-weight: 200;
			}
		}

		.btn {
			color: #f06c7a;
			width: 100%;
			height: 90upx;
			display: flex;
			justify-content: center;
			align-items: center;
			border-radius: 45upx;
			background-color: #fff;
			font-size: 40upx;
		}
	}

	.userform {
		.username {
			position: relative;

			.get-code {
				position: absolute;
				height: 90upx;
				display: flex;
				align-items: center;
				justify-content: center;
				right: 0;
				padding: 0 40upx;
				z-index: 3;

				&:after { //点击以后,左边出现白色的线
					content: " ";
					width: 1upx; //宽度为1upx
					height: 50upx; //高度为50upx
					background-color: #fff;  //背景颜色为白色
					position: absolute;
					z-index: 3;
					margin-right: 100%;
					left: 0;
					top: 20upx;
				}
			}
		}

		.res {
			display: flex;
			justify-content: center;
			align-items: center;
			height: 100upx;
			color: rgba($color: #ffffff, $alpha: 0.8);
		}
	}
</style>

  • 25
    点赞
  • 117
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
Uni-app是一款跨平台开发框架,而Uni-Cloud则是一个为开发者提供云端服务的平台。实现图形验证码可以使用Uni-Cloud的云函数功能,具体步骤如下: 1. 在Uni-Cloud中创建一个云函数,命名为`getVerificationCode`; 2. 在云函数中引入`jimp`模块,用于生成验证码图片。 ```javascript const jimp = require('jimp'); ``` 3. 定义生成验证码的函数`generateCode`,该函数接受两个参数,分别是验证码长度和验证码图片的宽度和高度。 ```javascript async function generateCode(length, width, height) { const code = [...Array(length)].map(() => (~~(Math.random() * 36)).toString(36)).join(''); const image = new jimp(width, height, '#fff'); const font = await jimp.loadFont(jimp.FONT_SANS_64_BLACK); image.print(font, 0, 0, code); return { code, buffer: await image.getBufferAsync(jimp.MIME_PNG) }; } ``` 4. 在云函数的主函数中,调用`generateCode`函数生成验证码,并将验证码的`code`和图片的`buffer`返回给前端。 ```javascript exports.main = async (event) => { const { length = 4, width = 200, height = 100 } = event.queryStringParameters || {}; const { code, buffer } = await generateCode(length, width, height); return { code: 0, message: 'success', data: { code, buffer: buffer.toString('base64') } }; }; ``` 5. 在前端页面中,通过Uni-Cloud的API调用云函数,获取验证码图片的`base64`编码,并将其显示在页面上。 ```javascript uniCloud.callFunction({ name: 'getVerificationCode', data: { length: 4, width: 200, height: 100 }, success(res) { const { code, buffer } = res.result.data; if (code === 0) { const base64ImgUrl = `data:image/png;base64,${buffer}`; // 将base64编码转换成图片并显示在页面上 } }, fail(err) { console.error(err); } }); ``` 以上就是使用Uni-Cloud实现图形验证码的步骤。需要注意的是,本示例仅供参考,实际使用时还需要进行适当的修改和优化。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值