代码封装 记得单独调用

import {preferences} from "@kit.ArkData"
import { common } from "@kit.AbilityKit";
import { BusinessError } from "@kit.BasicServicesKit";
type ValueType = number | string | boolean | Array<number> | Array<string> | Array<boolean> | Uint8Array | object | bigint
export class PreferenceStore{
  static preferenceStore:preferences.Preferences|null=null
  /**
   * 初始化用户首选项
   * @param context
   */
  static initPreferences(context:common.UIAbilityContext){
    let options:preferences.Options={name:'myStore'}
    PreferenceStore.preferenceStore=preferences.getPreferencesSync(context,options)
    console.log('初始化了存储')
  }
  /**
   * 设置本地存储并做持久化
   * @param name
   * @param value
   */
  static set(name:string,value:ValueType){
    PreferenceStore.preferenceStore?.putSync(name,value)
    console.log('做了存储')
    //做本地存储持久化
    PreferenceStore.preferenceStore?.flush((err: BusinessError) => {
      if (err) {
        console.error(`Failed to flush. Code:${err.code}, message:${err.message}`);
        return;
      }
      console.info('成功持久化.');
    })
  }
  /**
   * 读取本地存储
   * @param name
   * @returns
   */
  static get(name:string){
   return PreferenceStore.preferenceStore?.getSync(name,"")
  }
  /**
   * 删除本地存储
   * @param name
   */
  static remove(name:string){
    PreferenceStore.preferenceStore?.deleteSync(name)
  }
  /**
   * 更多请参阅文档
   */
}

EntryAbility.ets文件里做初始化

  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/preferences/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.');
    });
    
    //初始化用户首选项,记得先导入!!!!!!!!!
    PreferenceStore.initPreferences(this.context)
  }

鸿蒙用户首选项API参考icon-default.png?t=O83Ahttps://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-data-preferences-V5#valuetype

鸿蒙用户首选项参阅指南icon-default.png?t=O83Ahttps://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/data-persistence-by-preferences-V5

Logo

欢迎加入 MCP 技术社区!与志同道合者携手前行,一同解锁 MCP 技术的无限可能!

更多推荐