一、简易验证码倒计时,需要调整一下样式,主题逻辑是:
1、通过countdownDisplay判断显示内容,false问显示文字,true为显示数字,默认为false
2、点击文字 countdownDisplay 置为true,并且调用this.setShowTime();获取倒计时,second这个字段控制倒计时显示
3、setShowTime控制倒计时的执行结束
// 展示显示文字,还是倒计时
@State countdownDisplay: boolean = false
// 倒计时
@State second: number = 59
// setInterval的执行ID,停止的时候需要用到
@State intervalID: number = 0
// 代码正文
build() {
Column() {
Column({ space: 10 }) {
this.MobilePhone()
Divider()
this.CodeLine()
Divider()
}
.width(CommonConstants.FULL_PERCENT)
.padding($r('app.float.vp_twelve'))
}
.width(CommonConstants.FULL_PERCENT)
.borderRadius({ topLeft: 25, topRight: 25 })
.backgroundColor(Color.White)
}
@Builder MobilePhone() {
Row() {
this.Login_Image($r('app.media.ic_mobile_phone'), $r('app.float.vp_twenty_four'), $r('app.float.vp_twenty_four'))
TextInput({ placeholder: '请输入手机号码' })
.Mobile_InputText_Style()
.onChange((val) => {
this.userMobile = val
})
}.width(CommonConstants.FULL_PERCENT)
}
@Builder CodeLine() {
Row() {
this.Login_Image($r('app.media.ic_code'), $r('app.float.vp_twenty_four'), $r('app.float.vp_twenty_four'))
Stack({ alignContent: Alignment.End }) {
TextInput({ placeholder: '请输入验证码' })
.backgroundColor(Color.White)
.type(InputType.Number)
.onChange((val) => {
this.code = val
})
if (this.countdownDisplay) {
Button() {
Text(JSON.stringify(this.second))
.fontColor($r('app.color.log_out'))
.fontSize($r('app.float.fp_twelve'))
}.Login_Code_Button()
} else {
Button() {
Text(this.codeText)
.fontColor($r('app.color.log_out'))
.fontSize($r('app.float.fp_twelve'))
}.Login_Code_Button()
.onClick(() => {
this.getCodeInfo()
})
}
}
.layoutWeight(1)
.margin({ right: 20 })
}
.width(CommonConstants.FULL_PERCENT)
}
// 倒计时逻辑
setShowTime() {
this.intervalID = setInterval(() => {
this.second--
if (this.second === 0) {
this.countdownDisplay = !this.countdownDisplay
this.second = 59
clearInterval(this.intervalID);
}
}, 1000)
}
// 样式,根据自己的UI调整
@Extend(Button) function Login_Code_Button() {
.width($r('app.float.vp_eighty'))
.height($r('app.float.vp_twenty_eight'))
.borderWidth($r('app.float.vp_one'))
.borderRadius($r('app.float.vp_eight'))
.borderColor($r('app.color.log_out'))
.backgroundColor(Color.White)
.type(ButtonType.Normal)
}