HarmonyOS Next应用开发实战——登录页面实现(part2)

110 阅读1分钟
3. 登录方式切换

支持密码登录和验证码登录两种方式,用户可以通过点击相应文本进行切换。

if (this.isPwdLgn) {
  Text('密码登录')
    .fontSize(CommonConstants.M_FONT_SIZE)
    .fontColor($r('app.color.main_color'))
    .margin({ top: '20vp' })
    .onClick(() => {
      this.isPwdLgn = !this.isPwdLgn;
      this.isCodeLgn = !this.isCodeLgn;
    })
} else {
  Text('验证码登录')
    .fontSize(CommonConstants.M_FONT_SIZE)
    .fontColor($r('app.color.main_color'))
    .margin({ top: '20vp' })
    .onClick(() => {
      this.isCodeLgn = !this.isCodeLgn;
      this.isPwdLgn = !this.isPwdLgn;
      promptAction.showToast({
        message: '手机号格式错误',
        duration: CommonConstants.ADVERTISING_INTERVAL_TIME,
      })
      return
    })
}
4. 协议勾选与登录验证

用户需要勾选《用户协议》和《隐私条款》才能进行登录操作,登录按钮的可用性根据输入内容进行判断。

Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) {
  Checkbox({ name: 'isAgree' })
    .select($$this.isAgree)
    // ...
}

Button('密码登录', { type: ButtonType.Normal })
  .enabled(isLoginClickable(this.phone))
  .onClick(() => {
    if (this.isAgree) {
      this.isPwdIptShow = !this.isPwdIptShow;
    } else {
      promptAction.showToast({
        message: '请勾选同意《用户协议》和《隐私政策》',
        duration: CommonConstants.ADVERTISING_INTERVAL_TIME,
      })
      return
    }
  })
5. 登录跳转

当用户输入有效信息并点击登录按钮后,页面会跳转到指定页面。

Button('登录', { type: ButtonType.Normal })
  .enabled(this.isCodeLgn ? (this.password.length > 5 ?? false)
    : this.password != '')
  .onClick(() => {
    this.pageInfos.replacePath({ name: 'TabPage' }, false);
  })

通过以上核心功能的实现,开发者可以在HarmonyOS Next应用中创建一个功能丰富、交互良好的登录页面。