HarmonyOS token和用户信息保存?

用户的登录token和用户信息的持久化存储demo

阅读 445
1 个回答

参考如下demo能否满足您的需求:

import router from '@ohos.router';
PersistentStorage.persistProp('token', '')
@Entry @Component
struct Index {
  @State message: string = '这是登录页';
  private title: string = "手机号登录"
  private backColor: ResourceColor = "#DC143C"
  @StorageLink('token') token: string = ''
  onPageShow() {
    if (this.token.length>0 && this.token !== "undefined"){
      console.log('登录页 onPageShow token有值 说明之前 有登录过 直接跳转到首页' + this.token)
      this.goToHome()
    }else {
      console.log('登录页 onPageShow token没值 说明之前 没登录过')
    }
  }
  build() {
    Stack(){
      Text(this.message + this.token)
        .fontSize(50)
        .fontWeight(FontWeight.Bold)
        .margin({ top:200 })
      Button()
        .type(ButtonType.Capsule)
        .width('100%')
        .height('50')
        .backgroundColor(this.backColor)
        .border({ color:'#CCCCCC', width:1 })
        .margin({ top:500 })
      Row(){
        Text(this.title)
          .fontSize(18)
          .fontColor('#333333')
        Text('(上次登录)')
          .fontSize(14)
          .fontColor('#C0C0C0')
      }
      .width('100%')
      .height('100%')
      .justifyContent(FlexAlign.Center)
      .onClick(() =>{
        this.mobilePhoneLoginClick()
      })
      .margin({ top:500 }) //.backgroundColor('#32CD32')
  }
  .width('90%')
  .height('50') //.backgroundColor('#00BFFF')
  }
  mobilePhoneLoginClick(){
    console.info('手机号登录 点击')
    this.loginSuccess()
  }
  loginSuccess(){
    let token = 'abc123456'
    console.info('登录成功 存本地的 token:' + token)
    AppStorage.setOrCreate('token',token)
    this.goToHome()
  }
  goToHome(){
    console.info('跳转到 首页')
    router.pushUrl({ url: 'pages/Home' })
  }
}

//下面是Home.ets页面

@Entry @Component
struct Home {
  @State message: string = '这是首页';
  @State token: string = ''
  onPageShow() {
    this.token = AppStorage.get('token') + ''
    console.info('首页 取存在本地的 temp:' + this.token)
  }
  build() {
    Row() {
      Column() {
        Text(this.message + this.token)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
      }
      .width('100%')
    }
    .height('100%')
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进