uni-app 开发小程序中,表单登录注册中,经常用到通过手机号获取验证码,在这里分享一下自己写的。
效果图
html代码如下:
<view class="list">
<view class="label"><span>*</span>手机号 </view>
<view class="right">
<input type="number" placeholder="请输入" @blur="phoneBlur" v-model="formData.mobile"
placeholder-style="colo人:#A1A2A1;font-size:28rpx">
</view>
</view>
<view class="list">
<view class="label"><span>*</span>验证码</view>
<view class="right">
<input type="number" placeholder="请输入" v-model="formData.checkCode"
placeholder-style="colo人:#A1A2A1;font-size:28rpx">
<button class="send-code" :disabled="disabled" @click="sendCode">{{sendTxt}}</button>
</view>
</view>
js 代码如下:
<script>
export default {
components: {
},
data() {
return {
formData: {},
timer: 60,
sendTxt: '获取验证码',
disabled: false,
}
},
methods: {
phoneBlur() {
var pattern = /^((0\d{2,3}-\d{7,8})|(1[3456789]\d{9}))$/;
if (pattern.test(this.formData.mobile)) {
return true;
} else {
uni.showToast({
icon: 'none',
title: '请输入正确的电话格式'
})
this.formData.mobile = '';
return false;
}
},
// 发送验证码
async sendCode() {
let that = this;
if (that.formData.mobile.length <= 0) {
uni.showToast({
icon: 'none',
title: '请输入手机号'
})
return;
} else if (that.formData.mobile.length < 11) {
uni.showToast({
icon: 'none',
title: '手机号不符合要求'
})
return;
} else {
that.disabled = true;
let timer1 = setInterval(() => {
that.timer--;
that.sendTxt = +that.timer + '秒重新发送';
if (that.timer == 0) {
clearInterval(timer1);
that.timer = 60;
that.disabled = false;
that.sendTxt = '发送验证码';
return;
}
}, 1000);
//获取验证的后端接口在此写
}
},
}
};
</script>
css代码如下:
<style lang="scss" scoped>
.list {
margin-top: 27rpx;
}
.label {
font-size: 36rpx;
font-weight: 400;
color: #333333;
padding-left: 27rpx;
margin-bottom: 11rpx;
span {
color: #FC5756;
}
}
.right {
width: 660rpx;
height: 90rpx;
background: #F8F9FD;
border-radius: 45rpx;
line-height: 90rpx;
display: flex;
align-items: center;
justify-content: space-between;
padding-left: 30rpx;
font-size: 30rpx;
font-weight: 400;
color: #999999;
input {
font-size: 34rpx;
display: inline-block;
}
.send-code {
width: 200rpx;
height: 50rpx;
background: #ECECEC;
border-radius: 25rpx;
font-size: 30rpx;
font-weight: 400;
color: #333333;
line-height: 50rpx;
text-align: center;
margin-right: 0;
margin-left: 0;
padding-left: 0;
padding-right: 0;
}
}
</style>
uni-app 小程序注册时,经常用到手机号获取验证码功能,记录一下。