#HarmonyOS NEXT体验官#鸿蒙实现用户的登录和注册 原创

小黄要努力
发布于 2024-7-31 13:07
浏览
0收藏

正所谓万丈高楼平地起,辉煌只能靠自己!!

#HarmonyOS NEXT体验官#鸿蒙实现用户的登录和注册-鸿蒙开发者社区

我们应用开发也理应如此,所有的应用一开始都必须要实现的两个功能。

没错!你猜的很对,就是我们梦开始的地方,是用户的登录与注册。

登录与注册可谓是每个app最重要的功能,用户信息贯穿了整个app的生命周期中,可见其地位的轻重。

#HarmonyOS NEXT体验官#鸿蒙实现用户的登录和注册-鸿蒙开发者社区

应用场景

用户的注册可以帮助我们更好的对用户信息进行保存分类,继而对用户进行进入app后的后续服务。

用户的登录可以对用户身份信息进行校验,我们可以用正确的信息登录到各种已经注册过的系统中,进行想要的服务和操作=


实现效果

今天我们来通过用户首选项来实现用户注册到登录的完整流程,跟着我的节奏,开始发车!!!(实现的效果如下)

登录

应用场景

用户的注册可以帮助我们更好的对用户信息进行保存分类,继而对用户进行进入app后的后续服务。

用户的登录可以对用户身份信息进行校验,我们可以用正确的信息登录到各种已经注册过的系统中,进行想要的服务和操作=


实现效果

今天我们来通过用户首选项来实现用户注册到登录的完整流程,跟着我的节奏,开始发车!!!(实现的效果如下)

登录

#HarmonyOS NEXT体验官#鸿蒙实现用户的登录和注册-鸿蒙开发者社区

#HarmonyOS NEXT体验官#鸿蒙实现用户的登录和注册-鸿蒙开发者社区

功能分析

1. 拿到用户注册信息

2. 拿到用户输入信息

3. 输入信息与注册信息进行对比,相同则登录成功,不同则提醒用用户


用户注册信息我们需要保存在本地所以需要用到用户首选项进行实现

首先对用户首选项进行简单的介绍

用户首选项为应用提供Key-Value键值型的数据处理能力,支持应用持久化轻量级数据,并对其修改和查询。当用户希望有一个全局唯一存储的地方,可以采用用户首选项来进行存储。Preferences会将该数据缓存在内存中,当用户读取的时候,能够快速从内存中获取数据

运作机制如下图

#HarmonyOS NEXT体验官#鸿蒙实现用户的登录和注册-鸿蒙开发者社区

我们通过api文档来对用户首选项进行一个简单的封装,更加方便的实现我们想要的效果(代码如下)

export class StorageUtils {



  /**
   * 获取Prefer实例
   * @param preferenceName
   * @returns
   */
  static async getPreferences(preferenceName: string = defaultPreferenceName) {
    return await dataPreferences.getPreferences(context, preferenceName)
  }

  static async put(key: string, value: ValueType, preferenceName: string = defaultPreferenceName) {
    if (preferenceName!==null) {
      // 获取实例
      let preferences = await this.getPreferences(preferenceName)
       preferences.put(key, value)
       preferences.flush()
    }

  }
  /**
   * 获取值
   * @param key
   * @param defaultValue
   * @param preferenceName
   * @returns
   */
  static async get(key: string, defaultValue: ValueType = "", preferenceName: string = defaultPreferenceName) {
    // 获取实例
    let preferences = await this.getPreferences(preferenceName)
    return preferences.get(key, defaultValue)
  }

 
}

封装完成之后我们开始在登录页面进行ui方面的实现,先使用text、textinput、button组件来绘制我们的登录界面,并且添加相应的逻辑,如果用户名称和密码有一个没有输入我们让登录按钮显示不同的状态,要想实现需要先定义几个对应的参数(实现代码如下)


未全部输入显示效果如下

#HarmonyOS NEXT体验官#鸿蒙实现用户的登录和注册-鸿蒙开发者社区

用户输入信息符合条件后显示效果如下

#HarmonyOS NEXT体验官#鸿蒙实现用户的登录和注册-鸿蒙开发者社区

填写密码"})
            .width(200)
            .placeholderColor(Color.Grey)
            .margin({left:36})
            .onChange((value:string)=>{
              if (value==='') {
                this.isPsw=false
              }else {
                this.isPsw=true
              }
              this.valuePsw=value

            })
        }
        .padding({left:20})
        .margin({top:20})
        .width('100%')


        Row(){
          Text("暂无账号?去注册")
            .fontColor("#ff2e76f5")
        }
        .padding({left:20})

        .onClick(()=>{
          if (this.save_acc!=""&&this.save_psw!="") {
            showToast("已经存在账号,请注销后重新注册")
          }else {
            router.pushUrl({url:RoutePath.REGISTER_PAGE})
          }

        })
        .width('100%')
        .margin({top:25,left:10})


      }


      Column(){
        Text("上述账号仅用于登录验证")
          .fontSize(14)
          .fontColor("#ff393535")

        Button("同意并继续")
          .fontSize(18)
          .fontColor(Color.White)
          .type(ButtonType.Normal)
          .borderRadius(5)
          .backgroundColor(this.isPhone&&this.isPsw?"#ff000000":"#C2C2C2")
          .width(180)
          .margin({top:35})
          .onClick(()=>{
            if (this.valuePhone.trim()===''&&this.valuePsw.trim()==='') {
              promptAction.showToast({duration:2000,message:"请输入手机号或密码"})
            }else {
              if (this.valuePhone==this.save_acc&&this.valuePsw==this.save_psw) {

                router.replaceUrl({url:RoutePath.HOME_INDEX_PAGE})
              }else {
                console.log("====="+this.valuePhone)
                console.log(this.valuePsw)
                showToast("账号或密码错误")
              }

            }

          })
        Row(){

        }
        .margin({top:45,bottom:20})
      }
    }.justifyContent(FlexAlign.SpaceBetween)
    .backgroundColor(Color.White)
    .height('100%')
    .width('100%')

  }

实现完成之后,实现用户首选项中查询数据的方法,我们点击提交按钮的时候要进行怕判断

(代码如下)


如果错误会提示用户

#HarmonyOS NEXT体验官#鸿蒙实现用户的登录和注册-鸿蒙开发者社区

async onPageShow(){

    await  this.initAccPreference()
    await  this.initPswPreference()
  }



  async initAccPreference(){
    if (!TextUtils.isEmpty(await this.getAccPreference())) {
      var s=await this.getAccPreference()
      let data:string=JSON.parse(s)
      this.save_acc=data
      console.log("userInfo_acc"+data)

    }
  }
  async initPswPreference(){
    if (!TextUtils.isEmpty(await this.getPswPreference())) {
      var s=await this.getPswPreference()
      let data:string=JSON.parse(s)
      this.save_psw=data
      console.log("userInfo_psw"+data)

    }
  }

  async getAccPreference(): Promise<string> {
    let theme: string = ''
    theme = await StorageUtils.get('acc') as string
    return theme
  }


  async getPswPreference(): Promise<string> {
    let theme: string = ''
    theme = await StorageUtils.get('pwd') as string
    return theme
  }

如果没有用户,提醒去注册,通过router跳转到对应页面去注册
onClick(()=>{
          if (this.save_acc!=""&&this.save_psw!="") {
            showToast("已经存在账号,请注销后重新注册")
          }else {
            router.pushUrl({url:RoutePath.REGISTER_PAGE})
          }

这样我们登录页面的UI和逻辑就实现成功了

注册页面我们要实现ui逻辑的同时,还需要把用户填写的数据添加进用户首选项中,如果用户名称和密码有一个没有输入我们让登录按钮显示不同的状态,要想实现需要先定义几个对应的参数(代码如下)


未输入状态显示如图


#HarmonyOS NEXT体验官#鸿蒙实现用户的登录和注册-鸿蒙开发者社区

输入后如下图所示

#HarmonyOS NEXT体验官#鸿蒙实现用户的登录和注册-鸿蒙开发者社区

@State valuePhone:string=''
  @State valuePsw:string=''
  @State isPhone:boolean=false
  @State isPsw:boolean=false

  Column(){
      Column(){
        Text("用户注册")
          .fontSize(22)
          .margin({top:40})
        Row(){
          Text("账号")
            .margin({left:10})
          TextInput({placeholder:"请填写账号"})
            .width(200)
            .placeholderColor(Color.Grey)
            .margin({left:36})
            .onChange((value:string)=>{
              if (value==='') {
                this.isPhone=false
              }else {
                this.isPhone=true
              }
              this.valuePhone=value
            })
        }
        .padding({left:20})
        .onAreaChange((oldValue: Area, newValue: Area) => {
          new Number(newValue.width).valueOf()
         new Number(newValue.height).valueOf()
        })
        .margin({top:40})
        .width('100%')

        Row(){
          Text("密码")
            .margin({left:10})
          TextInput({placeholder:"请填写密码"})
            .width(200)
            .placeholderColor(Color.Grey)
            .margin({left:36})
            .onChange((value:string)=>{
              if (value==='') {
                this.isPsw=false
              }else {
                this.isPsw=true
              }
              this.valuePsw=value
            })
        }
        .padding({left:20})
        .margin({top:20})
        .width('100%')

      }


      //bottom
      Column(){
        Text("上述账号仅用于注册验证")
          .fontSize(14)
          .fontColor("#ff393535")

        Button("注册")
          .fontSize(18)
          .fontColor(Color.White)
          .type(ButtonType.Normal)
          .borderRadius(5)
          .backgroundColor(this.isPhone&&this.isPsw?"#ff080709":"#C2C2C2")
          .width(180)
          .margin({top:35,bottom:50})
          .onClick(()=>{
            if (this.valuePhone===''&&this.valuePsw==='') {
              promptAction.showToast({duration:2000,message:"请输入手机号或密码"})
            }else {
              StorageUtils.put("acc",this.valuePhone)
              StorageUtils.put("pwd",this.valuePsw)
              promptAction.showToast({duration:2000,message:"注册成功"})
              router.back({url:RoutePath.LOGIN_PAGE})
            }

          })



      }



    }.justifyContent(FlexAlign.SpaceBetween)
    .backgroundColor(Color.White)
    .height('100%')
    .width('100%')

  }

 	UI跟我们的登录页面差不多,我们需要对定义的参数进行判断,然后提交存入用户首选项中,进行登录,业务逻辑都在点击事件里进行处理

onClick(()=>{
            if (this.valuePhone.trim()===''&&this.valuePsw.trim()==='') {
              promptAction.showToast({duration:2000,message:"请输入手机号或密码"})
            }else {
              if (this.valuePhone==this.save_acc&&this.valuePsw==this.save_psw) {

                router.replaceUrl({url:"pages/Index"})
              }else {
                console.log("====="+this.valuePhone)
                console.log(this.valuePsw)
                showToast("账号或密码错误")
              }

            }

          })

登录成功后使用router 跳转页面

#HarmonyOS NEXT体验官#鸿蒙实现用户的登录和注册-鸿蒙开发者社区

到这里,我们的鸿蒙登录注册功能就实现完成了,赶快去试试吧

©著作权归作者所有,如需转载,请注明出处,否则将追究法律责任
分类
标签
收藏
回复
举报
回复
    相关推荐