鸿蒙项目二—— 注册和登录

此部分和上篇文章是连续剧 ,如果需要,请查看

一、注册

复制代码
import http from '@ohos.net.http';
@Entry
@Component
struct Reg {

  // 定义数据:
  @State username: string = "";
  @State userpass: string = "";
  @State userpass2: string = "";
  @State usernameColor: number = 0x000000;
  @State userpassColor: number = 0x000000;
  @State userpass2Color: number = 0x000000;

  // 表单验证是否成功:
  formIsSuccess() {
    return this.username.trim() !== "" && this.userpass.trim() !== "" && this.userpass2.trim() !== "" && this.userpass === this.userpass2
  }

  regSave() {
    //   1、非空验证
    if (this.username.trim() == "") {
      console.log("用户名不能为空")
      this.usernameColor = 0xff0000;
      return;
    }

    if (this.userpass.trim() == "") {
      console.log("密码不能为空")
      this.userpassColor = 0xff0000;
      return;
    }
    if (this.userpass2.trim() == "") {
      console.log("确认密码不能为空")
      this.userpass2Color = 0xff0000;
      return;
    }
    //   2、密码是否一致

    //   3、发送请求,进行注册
    const httpRequest = http.createHttp();
    httpRequest.request("http://localhost:3000/vips", {
      method: http.RequestMethod.POST, // 可选,默认为http.RequestMethod.GET
      // 开发者根据自身业务需要添加header字段
      header: {
        'Content-Type': 'application/json'
      },
      // 当使用POST请求时此字段用于传递内容
      extraData: {
          username:this.username,
          userpass:this.userpass
      },
      connectTimeout: 60000, // 可选,默认为60s
      readTimeout: 60000, // 可选,默认为60s
    },(err,data)=>{
        if(!err){
          console.log("data.result",data.result)
          console.log("data.responseCode",data.responseCode)
          if(data.responseCode==201){
            console.log("注册成功")
          }
        }
    })
  }

  build() {
    Column() {
      Row() {
        Image($r("app.media.back")).width(50).height(30).margin(20)
      }
      .width("100%")
      .height(60)

      Blank().height(50)
      Row() {
        Text("欢迎您的注册")
          .fontSize(40)
          .fontWeight(FontWeight.Bold)
      }

      Row() {
        Text("用户名:").fontSize(20).fontWeight(400)
        TextInput({ placeholder: "请输入用户名", text: this.username }).width(260).height(40)
          .placeholderColor(this.usernameColor)
          .onChange((val: string) => {
            this.username = val;
          })
      }.width("100%")
      .height(60)
      .margin({
        top: 20
      })

      Row() {
        Text("密    码:").fontSize(20).fontWeight(400)
        TextInput({ placeholder: "请输入密码", text: this.userpass })
          .type(InputType.Password)
          .width(260)
          .height(40)
          .placeholderColor(this.userpassColor)
          .onChange((val: string) => {
            this.userpass = val;
          })
      }.width("100%")
      .height(60)
      .margin({
        top: 10
      })

      Row() {
        Text("确认密码:").fontSize(20).fontWeight(400)
        TextInput({ placeholder: "请输入确认密码", text: this.userpass2 })
          .type(InputType.Password)
          .width(260)
          .height(40)
          .placeholderColor(this.userpass2Color)
          .onChange((val: string) => {
            this.userpass2 = val;
          })
      }.width("100%")
      .height(60)
      .margin({
        top: 10
      })

      Row() {
        if (this.userpass !== this.userpass2) {
          Text("两次密码不一致").fontSize(20).fontColor(Color.Red);
        }
      }

      Button("注册")
        .width("90%")
        .height(60)
        .margin({
          top: 10
        })
        .fontSize(30)
        .fontWeight(600)
        .enabled(this.formIsSuccess())
        .onClick(() => {
          this.regSave();
        })

      Blank().height(100)
      Row() {
        Text("--第三方账号登录--")
      }.margin({
        bottom: 20
      })

      Flex({ justifyContent: FlexAlign.SpaceEvenly, alignItems: ItemAlign.Center }) {
        Image($r("app.media.qq")).width(40).height(40)
        Image($r("app.media.weixin")).width(40).height(40)
        Image($r("app.media.weibo")).width(40).height(40)
      }.width("100%")
      .height(60)

    }
    .width('100%')
  }
}

二、登录

本地存储用户信息的文件:

`utils/globaldata.ts`

复制代码
export const storage:LocalStorage = new LocalStorage();

页面代码:

复制代码
import http from '@ohos.net.http';
import router from '@ohos.router';
import {storage} from '../utils/globaldata';

interface IParams{
  from:string,
  data:string
}

@Entry
@Component
struct Login {

  // 定义数据:
  @State username: string = "";
  @State userpass: string = "";
  @State phone:string="";

  @State usernameColor: number = 0x000000;
  @State userpassColor: number = 0x000000;

  // 表单验证是否成功:
  formIsSuccess() {
    return this.username.trim() !== "" && this.userpass.trim() !== "";
  }

  loginCheck() {
    //   1、非空验证
    if (this.username.trim() == "") {
      console.log("用户名不能为空")
      this.usernameColor = 0xff0000;
      return;
    }

    if (this.userpass.trim() == "") {
      console.log("密码不能为空")
      this.userpassColor = 0xff0000;
      return;
    }

    //3、发送请求,进行登录
    const httpRequest = http.createHttp();

    // get请求,给后端传递数据的方式一:
    // 请求地址?属性名1=属性值1&属性名2=属性值2
    httpRequest.request(`http://localhost:3000/vips?username=${this.username}&userpass=${this.userpass}`,(err,data)=>{
      // !err 只是表示请求响应没有问题,不代表是否获取到了数据
      if(!err){
        console.log("data.result",data.result)
        const arr = JSON.parse(data.result as string)
        if(arr.length===1){
          console.log("登录成功");
          // 保存登录的相关信息(如:用户名,电话号码)
          storage.setOrCreate("username",this.username);
          storage.setOrCreate("phone",this.phone);
          console.log("from",(router.getParams() as IParams).from)
          // 跳转到我的页面。
          // router.back();
          router.pushUrl({
            url:(router.getParams() as IParams).from,
            params:{
              data:(router.getParams() as IParams).data
            }
          })
        }else{
          console.log("登录失败,用户名或密码不正确")
        }
      }else{
        console.log("网络出错")
      }
    })
  }

  build() {
    Column() {
      Row() {
        Image($r("app.media.back")).width(50).height(30).margin(20).onClick(()=>{
          router.back();
        })
      }
      .width("100%")
      .height(60)

      Blank().height(50)
      Row() {
        Text("亲,请登录")
          .fontSize(40)
          .fontWeight(FontWeight.Bold)
      }

      Row() {
        Text("用户名:").fontSize(20).fontWeight(400)
        TextInput({ placeholder: "请输入用户名", text: this.username }).width(260).height(40)
          .placeholderColor(this.usernameColor)
          .onChange((val: string) => {
            this.username = val;
          })
      }.width("100%")
      .height(60)
      .margin({
        top: 20
      })

      Row() {
        Text("手机号码:").fontSize(20).fontWeight(400)
        TextInput({ placeholder: "请输入手机号", text: this.phone }).width(260).height(40)
          .placeholderColor(this.usernameColor)
          .onChange((val: string) => {
            this.phone = val;
          })
      }.width("100%")
      .height(60)
      .margin({
        top: 20
      })

      Row() {
        Text("密    码:").fontSize(20).fontWeight(400)
        TextInput({ placeholder: "请输入密码", text: this.userpass })
          .type(InputType.Password)
          .width(260)
          .height(40)
          .placeholderColor(this.userpassColor)
          .onChange((val: string) => {
            this.userpass = val;
          })
      }.width("100%")
      .height(60)
      .margin({
        top: 10
      })

      Button("登录")
        .width("90%")
        .height(60)
        .margin({
          top: 10
        })
        .fontSize(30)
        .fontWeight(600)
        .enabled(this.formIsSuccess())
        .onClick(() => {
          this.loginCheck();
        })

      Blank().height(100)
      Row() {
        Text("--第三方账号登录--")
      }.margin({
        bottom: 20
      })

      Flex({ justifyContent: FlexAlign.SpaceEvenly, alignItems: ItemAlign.Center }) {
        Image($r("app.media.qq")).width(40).height(40)
        Image($r("app.media.weixin")).width(40).height(40)
        Image($r("app.media.weibo")).width(40).height(40)
      }.width("100%")
      .height(60)

    }
    .width('100%')
  }
}
相关推荐
(╹◡╹)11 分钟前
11.RK3588本地大模型内存评估优化
java·linux·前端
电气研究所29 分钟前
Java + Redis 实现工业设备告警去抖,避免变频器故障重复推送
java·前端
AI视觉网奇33 分钟前
cannot import name ‘model_urls‘ from ‘torchvision.models.resnet‘
linux·前端·javascript
Vuji36 分钟前
深入 pi-agent 内核:完整追踪一次 CLI 交互的完整链路
前端·agent
zfoo-framework1 小时前
安装pi agent 支持duojie和deepseek
java·服务器·前端
l1m0_1 小时前
告别反复修改Prompt:AI生成React应用并落地开发的实战复盘
前端·react.js·ui·ai·设计
xexpertS1 小时前
前端工程转型实践:从 Ember 迁移到 React,提升构建速度与研发效能
前端·react.js·前端框架
大家的林语冰1 小时前
👍 JS 还在进化,ES2026 正式推出,最新七大特性补全!
前端·javascript·json
铁皮饭盒1 小时前
DeepSeek V4 Pro 0813发布了, 也可以部署到 Codex 了
前端·javascript·后端
贾伟康2 小时前
【华夏二十四节气|07】HarmonyOS 6.0.2(22) ArkTS 节气搜索实战:多字段匹配与四态闭环
移动开发·harmonyos·arkts·arkui·本地搜索