logo小熊博客
首页 fk标记语言示例 登录
目录
鸿蒙本地保存账号密码的表单示例
// LoginPage.ets
import { preferences } from '@kit.ArkData';
import { BusinessError } from '@kit.BasicServicesKit';
import { Context } from '@kit.AbilityKit';

@Entry
@Component
struct LoginPage {
  @State username: string = '';
  @State password: string = '';
  @State isLoading: boolean = false;

  private context: Context = getContext(this) as Context;
  private dataPreferences: preferences.Preferences | null = null;

  // 初始化偏好设置
  async aboutToAppear() {
    await this.initPreferences();
    await this.loadSavedCredentials();
  }

  // 初始化Preferences
  async initPreferences() {
    try {
      this.dataPreferences = await preferences.getPreferences(this.context, 'loginData');
    } catch (err) {
      console.error('初始化Preferences失败:', err);
    }
  }

  // 加载已保存的账号密码
  async loadSavedCredentials() {
    if (!this.dataPreferences) {
      return;
    }

    try {
      // 读取保存的账号
      const savedUsername = await this.dataPreferences.get('username', '') as string;
      const savedPassword = await this.dataPreferences.get('password', '') as string;

      if (savedUsername) {
        this.username = savedUsername;
      }
      if (savedPassword) {
        this.password = savedPassword;
      }

      console.info('成功加载保存的账号密码');
    } catch (err) {
      console.error('读取账号密码失败:', err);
    }
  }

  // 保存账号密码到本地
  async saveCredentials() {
    if (!this.dataPreferences) {
      return;
    }

    try {
      await this.dataPreferences.put('username', this.username);
      await this.dataPreferences.put('password', this.password);
      await this.dataPreferences.flush();
      console.info('账号密码保存成功');
    } catch (err) {
      console.error('保存账号密码失败:', err);
    }
  }

  // 登录处理
  async handleLogin() {
    if (!this.username || !this.password) {
      AlertDialog.show({
        title: '提示',
        message: '请输入账号和密码',
        autoCancel: true,
        alignment: DialogAlignment.Center,
        confirm: {
          value: '确定',
          action: () => {}
        }
      });
      return;
    }

    this.isLoading = true;

    try {
      // 保存账号密码到本地
      await this.saveCredentials();

      // 这里可以添加实际的登录逻辑
      // 模拟登录请求
      setTimeout(() => {
        this.isLoading = false;
        AlertDialog.show({
          title: '成功',
          message: '登录成功!账号密码已保存',
          autoCancel: true,
          alignment: DialogAlignment.Center,
          confirm: {
            value: '确定',
            action: () => {}
          }
        });
      }, 1000);

    } catch (err) {
      this.isLoading = false;
      console.error('登录失败:', err);
    }
  }

  // 清除保存的账号密码
  async clearCredentials() {
    if (!this.dataPreferences) {
      return;
    }

    try {
      await this.dataPreferences.delete('username');
      await this.dataPreferences.delete('password');
      await this.dataPreferences.flush();

      this.username = '';
      this.password = '';

      AlertDialog.show({
        title: '提示',
        message: '已清除保存的账号密码',
        autoCancel: true,
        alignment: DialogAlignment.Center,
        confirm: {
          value: '确定',
          action: () => {}
        }
      });
    } catch (err) {
      console.error('清除账号密码失败:', err);
    }
  }

  build() {
    Column() {
      // 标题
      Text('用户登录')
        .fontSize(28)
        .fontWeight(FontWeight.Bold)
        .margin({ top: 60, bottom: 40 })

      // 账号输入框
      Column() {
        Text('账号')
          .fontSize(14)
          .fontColor('#666')
          .width('100%')
          .margin({ bottom: 8 })

        TextInput({ text: this.username, placeholder: '请输入账号' })
          .type(InputType.Normal)
          .width('100%')
          .height(48)
          .fontSize(16)
          .backgroundColor('#F5F5F5')
          .borderRadius(8)
          .padding({ left: 12, right: 12 })
          .onChange((value: string) => {
            this.username = value;
          })
      }
      .width('85%')
      .margin({ bottom: 20 })

      // 密码输入框
      Column() {
        Text('密码')
          .fontSize(14)
          .fontColor('#666')
          .width('100%')
          .margin({ bottom: 8 })

        TextInput({ text: this.password, placeholder: '请输入密码' })
          .type(InputType.Password)
          .width('100%')
          .height(48)
          .fontSize(16)
          .backgroundColor('#F5F5F5')
          .borderRadius(8)
          .padding({ left: 12, right: 12 })
          .onChange((value: string) => {
            this.password = value;
          })
      }
      .width('85%')
      .margin({ bottom: 30 })

      // 登录按钮
      Button(this.isLoading ? '登录中...' : '登录')
        .width('85%')
        .height(48)
        .fontSize(18)
        .fontColor('#FFFFFF')
        .backgroundColor('#1890FF')
        .borderRadius(24)
        .enabled(!this.isLoading)
        .onClick(() => {
          this.handleLogin();
        })

      // 清除按钮
      Button('清除保存的账号密码')
        .width('85%')
        .height(40)
        .fontSize(14)
        .fontColor('#666')
        .backgroundColor('#F0F0F0')
        .borderRadius(20)
        .margin({ top: 20 })
        .onClick(() => {
          this.clearCredentials();
        })

      // 提示文本
      Text('首次登录后将自动保存账号密码')
        .fontSize(12)
        .fontColor('#999')
        .margin({ top: 20 })
    }
    .width('100%')
    .height('100%')
    .backgroundColor('#FFFFFF')
  }
}
上一篇:鸿蒙开发应用沉浸式效果
下一篇:鸿蒙tab切换
请我喝奶茶!
赞赏码
手机扫码访问
手机访问