ArKTS:login page using HarmonyOS's ArkUI

项目结构:

 

 

/**
 # encoding: utf-8
 # 版权所有  2025 ©涂聚文有限公司™ ®
 # 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
 # 描述:
 # Author    : geovindu,Geovin Du 涂聚文.
 # IDE       : DevEco Studio 5.1.1  HarmonyOS
 # os        : windows 10
 # database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
 # Datetime  : 2025/7/20 10:23
 # User      :  geovindu
 # Product   : DevEco Studio
 # Project   : MyApplication
 # File      : LoginPage.ets
 **/

import router from '@ohos.router'
import prompt from '@ohos.prompt'
import promptAction from '@ohos.promptAction'
import { TipsDialog, SelectDialog, ConfirmDialog, AlertDialog, LoadingDialog, CustomContentDialog } from '@kit.ArkUI';

import common from '@ohos.app.ability.common';
import { BusinessError } from '@ohos.base';
import preferences from '@ohos.data.preferences'; // 导入新的Preferences模块


@Entry
@Component
struct LoginPage {
  @State userName: string = '';
  @State password: string = '';
  @State rememberPassword: boolean = false;
  @State loading: boolean = false;
  @State errorMessage: string = '';
  private context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;


  build() {
    Column({space:'30vp'}) {
      Text("登陆")
        .fontSize('30vp')
        .fontWeight(FontWeight.Bold).margin({
        bottom: '10vp'
      })
      Row() {
        Text('用户名:')
          .fontSize('18vp')
          .fontWeight(FontWeight.Bold)
          .margin({
          left: '1%'
        })
      }.width("100%")
      Row() {
        //Image($r("app.media.username")).width(30).margin({ top: 80, bottom: 20 })
        TextInput({ placeholder: '请输入用户名', text: '' })
          .padding( {top: '0vp',
            right: '0vp',
            bottom: '0vp',
            left: '30vp'})
          .backgroundColor('#F0F0F0')
          .backgroundImage($r("app.media.username"),ImageRepeat.NoRepeat)
          .backgroundImagePosition(Alignment.Start)
          .backgroundImageSize({ width: '30vp', height: '30vp'})
          .placeholderColor(Color.Gray)
          .placeholderFont({
            size: '15vp',
            weight: FontWeight.Bold,
            family: '宋体'
          })
          .width('90%')
          .height('50vp')
          .margin({
            left: '2%',
          })
          .onChange((value: string) => {
            this.userName = value;
          })
      }.width("100%")
      Row() {
        Text('密码:').fontSize(18)
          .fontWeight(FontWeight.Bold)
          .margin({
            left: '1%'
          })
      }.width("100%")
      Row(){
        TextInput({placeholder: '请输入密码',text:''})
          .backgroundColor('#F0F0F0')
          .type(InputType.Password) //TextInputType.PASSWORD
          .placeholderColor(Color.Gray)
          .backgroundImage($r("app.media.password"),ImageRepeat.NoRepeat)
          .backgroundImagePosition(Alignment.Start)
          .backgroundImageSize({ width: 30, height: 30})
          .padding( {top: '0vp',
            right: '0vp',
            bottom: '0vp',
            left: '30vp'})
          .width('90%')
          .height(50)
          .margin({
            left:'2%'
          })
          .onChange((value: string) => {
            this.password = value;
          })
      }.width("100%")

      Row() {
        Button('登录')
          .width("50%").height('40vp').backgroundColor("#ff144ec4")
          .onClick(() => {
            if(this.userName === '') {
              promptAction.showToast({ message: '请输入用户名' })

            }
            else if(this.password === '') {
              promptAction.showToast({ message: '请输入密码' })
            }
            else if (this.userName === 'admin' && this.password === '123456') {
              console.info('登录成功')
              router.pushUrl({
                url: 'pages/Index',
              }).then(() => {
                console.info('跳转成功')
                console.log(this.userName)
                console.log(this.password)

              }).catch(() => {
                console.info('跳转失败')
              });
            } else {
              this.getUIContext().showAlertDialog(
                {
                  title: '提示',
                  message: '密码错误或为空',
                  autoCancel: true,
                  alignment: DialogAlignment.Bottom,
                  offset: { dx: 0, dy: -20 },
                  gridCount: 3,
                  confirm: {
                    value: '确定',
                    action: () => {
                      console.info('Button-clicking callback');
                    }
                  },
                  cancel: () => {
                    console.info('Closed callbacks');
                  },
                  onWillDismiss: (dismissDialogAction: DismissDialogAction) => {
                    console.info("reason=" + JSON.stringify(dismissDialogAction.reason));
                    console.info("dialog onWillDismiss");
                    if (dismissDialogAction.reason === DismissReason.PRESS_BACK) {
                      dismissDialogAction.dismiss();
                    }
                    if (dismissDialogAction.reason === DismissReason.TOUCH_OUTSIDE) {
                      dismissDialogAction.dismiss();
                    }
                  }
                }
              )

              console.info('用户名或密码错误' )
              //Toast.show('用户名或密码错误');
            }
          })
      }
      Row()
      {

        Button('注册')
        .onClick(() => {
          router.pushUrl({
            url: 'pages/RegisterPage',
          })
        })
        Button('忘记密码')
          .onClick(() => {
            router.pushUrl({
              url: 'pages/ForgetPasswordPage',
            })
          })
      }
      Row(){
        // 底部其他登录方式
        Column() {
          Text('第三方登录方式') //$r('app.string.other_login_methods')
            .fontSize('14vp')
            .fontColor('#999999')
            .margin({ top: 0, bottom: '10vp' })

          Row() {

            Image($r('app.media.icon_wechat')) //
              .width('40vp')
              .height('40vp')
              .onClick(() => {
                //this.handleWechatLogin();
              })

            Blank()

            Image($r('app.media.qq')) //
              .width('40vp')
              .height('40vp')
              .onClick(() => {
                //this.handleQQLogin();
              })

            Blank()

            Image($r('app.media.alipay')) //
              .width('40vp')
              .height('40vp')
              .onClick(() => {
                //this.handleAlipayLogin();
              })
          }
          .width('60%')

          Text() //$r('app.string.user_agreement')
            .fontSize('12vp')
            .fontColor('#999999')
            .margin({ top: '40vp', bottom: '20vp' })
        }.width('100%')

      }
      .height('40vp')
      .width('100%')
    }
    .height('100%')
    .width('100%')



  }

  // 处理登录逻辑
  handleLogin() {
    // 简单验证
    if (!this.userName) {
      //this.errorMessage = $r('app.string.username_empty');
      return;
    }

    if (!this.password) {
      //this.errorMessage = $r('app.string.password_empty');
      return;
    }

    this.errorMessage = '';
    this.loading = true;

    // 模拟登录请求
    setTimeout(() => {
      // 这里应该是实际的登录API调用
      if (this.userName === 'admin' && this.password === '123456') {
        // 登录成功
        if (this.rememberPassword) {
          // 保存用户名和密码到本地存储
          this.saveCredentials(this.userName, this.password);
        }

        // 跳转到主页
        this.navigateToMainPage();
      } else {
        // 登录失败
        //this.errorMessage = $r('app.string.login_failed');
      }

      this.loading = false;
    }, 1500);
  }

  // 保存凭证到本地存储
  saveCredentials(username: string, password: string) {
    try {
      // 实际开发中应使用加密存储
      //this.context.preferences.put('username', username);
      //this.context.preferences.put('password', password);
      //this.context.preferences.flush();
    } catch (error) {
      console.error(`Failed to save credentials: ${(error as BusinessError).message}`);
    }
  }

  // 跳转到忘记密码页面
  navigateToForgetPassword() {
    router.pushUrl({
      url: 'pages/ForgetPassword'
    });
  }

  // 跳转到注册页面
  navigateToRegister() {
    router.pushUrl({
      url: 'pages/Register'
    });
  }

  // 跳转到主页
  navigateToMainPage() {
    router.pushUrl({
      url: 'pages/MainPage'
    });
  }

  // 微信登录
  handleWechatLogin() {
    console.info('WeChat login clicked');
    // 实现微信登录逻辑
  }

  // QQ登录
  handleQQLogin() {
    console.info('QQ login clicked');
    // 实现QQ登录逻辑
  }

  // 支付宝登录
  handleAlipayLogin() {
    console.info('Alipay login clicked');
    // 实现支付宝登录逻辑
  }


}

  

 

 

 

https://developer.huawei.com/consumer/cn/doc/harmonyos-references/ohos-arkui-advanced-dialog

华为鸿蒙os开发官网
https://developer.huawei.com/consumer/cn/
HarmonyOS开发设计规范
https://developer.huawei.com/consumer/cn/design/
ArkUI方舟UI框架
https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/arkui-declarative-comp-V5

 

posted @ 2025-07-20 10:38  ®Geovin Du Dream Park™  阅读(27)  评论(0)    收藏  举报