鸿蒙通过用户首选项实现数据持久化

先将首选项的代码封装成一个类便于调用

将本地存储的方法封装成一个个的静态方法便于调用

//本地存储
export class PreferenceStorage{
  static dataPreferences: preferences.Preferences | null = null;
  // 初始化函数
  static init(context: common.UIAbilityContext) {
    let options: preferences.Options = { name: 'myStore' };
    PreferenceStorage.dataPreferences = preferences.getPreferencesSync(context, options);
  }
  // 设置本地数据
  static set(name:string,value:string){
    PreferenceStorage.dataPreferences?.putSync(name,value)
    PreferenceStorage.dataPreferences?.flush(err=>{
      console.log("本地首选项存储失败")
    })
  }
  //拿到本地数据
  static get(name:string){
    return PreferenceStorage.dataPreferences?.getSync(name,'') as string
  }
  //删除本地数据
  static del(name:string){
    PreferenceStorage.dataPreferences?.deleteSync(name)
  }

}

 在src/main/ets/EntryAbility里添加代码 (注释部分)

 onWindowStageCreate(windowStage: window.WindowStage): void {
    // Main window is created, set main page for this ability
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');

    windowStage.loadContent('pages/Index', (err) => {
      if (err.code) {
        hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
        return;
      }
      hilog.info(0x0000, 'testTag', 'Succeeded in loading the content.');
    });
    //加入这一行代码
    PreferenceStorage.init(this.context)
  }

使用例子:(例子给的比较简单,给出了在本地拿到数据和在本地设置数据)

将首选项引入使用首选项类中的静态方法(这个登录组件是存入数据)

import { promptAction } from '@kit.ArkUI';
//将用户首选项引入
import {PreferenceStorage} from '../utils/tool'
@Component
export struct LoginPage {
  pathStack:NavPathStack=new NavPathStack()
  @State message: string = 'Hello World';
  @State userName:string=""
  @State password:string=""
  build() {
    NavDestination(){
      Column({space:20}) {
        Row(){

        }
        .margin({
          top:50
        })
        .backgroundColor("#cecece")
        .width(150)
        .height(150)
        .borderRadius("50%")
        TextInput({
          placeholder:"请输入账号",
          text:$$this.userName
        })
        TextInput({
          placeholder:"请输入密码",
          text:$$this.password
        })
        Button("登录")
          .onClick(()=>{
            if(this.userName&&this.password){
               //登录调接口部分
               //把登录信息存储在本地
                PreferenceStorage.set("token","ooo")
            }else {
              promptAction.showToast({
                message:"请输入信息"
              })
            }

          })
      }
      .padding(20)
    }
    .onReady((context)=>{
      this.pathStack=context.pathStack
    })
    .title("登录")
  }
}

将首选项引入使用首选项类中的静态方法(这个登录组件是获取数据)

import {PreferenceStorage} from '../utils/tool'
@Component
export struct PersonCenter{
  pathStack:NavPathStack=new NavPathStack()
  @State token:string=''
  aboutToAppear(): void {
    //设置路由拦截器
    const that=this
    // this.token=PreferenceStorage.get("token")
    this.pathStack.setInterception({
      // 展示的时候执行
      didShow(){
        console.log(PreferenceStorage.get("token"))
        that.token=PreferenceStorage.get("token")
      }
    })
  }
  build() {
    Column({space:20}){
      Row(){

      }
      .margin({
        top:50
      })
      .backgroundColor("#cecece")
      .width(150)
      .height(150)
      .borderRadius("50%")
      Text(this.token)
      Button("登录")
        .onClick(()=>{
            this.pathStack.pushPath({
              name:"COM_LOGIN"
            })
        })
      Button("注册")
        .onClick(()=>{
          this.pathStack.pushPath({
            name:"COM_REG"
          })
        })
    }
    .height("100%")
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值