HarmonyOS ArkTs stage模式 實(shí)現(xiàn)preferences的輕量級(jí)儲(chǔ)存

項(xiàng)目中涉及到數(shù)據(jù)的儲(chǔ)存

導(dǎo)入依賴

import data_preferences from '@ohos.data.preferences';
import common from '@ohos.app.ability.common';

直接封裝了一個(gè)工具類大家可以學(xué)習(xí)一下

import data_preferences from '@ohos.data.preferences';
import common from '@ohos.app.ability.common';

/**
 * 輕量級(jí)緩存工具類
 */
const context = getContext(this) as common.UIAbilityContext;
let promise = data_preferences.getPreferences(context, 'mystore');

export class PreferencesUtils {

  /**
   * 
   * @param name 傳入的key
   * @param lhz 存儲(chǔ)字段的類型(我這里存儲(chǔ)的是string,所以直接寫死了)
   * @returns 獲取數(shù)據(jù)字段
   */
  static getPrefer(name): String {
    promise.then((res)=>{
      res.get(name,"lhz")
        .then((data:data_preferences.ValueType)=>{
          console.log("-------"+data.toString())
          return data.toString()
        })
    })
    return
  }

  /**
   * 
   * @param name 傳入的key
   * @param valuer 傳入的 value
   * 傳入需要儲(chǔ)存的字段
   */
  static putPrefer(name,valuer): void {
    promise.then((res)=>{
      res.put(name,valuer)
    })
  }
}

下面是引用工具類進(jìn)行put和get數(shù)據(jù)字段

  /**
   * name Key值
   * 姓名  value值
   * 存值
   */
PreferencesUtils.putPrefer('name','姓名')
  /**
   * name Key值
   * 取值
   */
PreferencesUtils.getPrefer('name')

大家有更好的方法可以評(píng)論,我都會(huì)看到,謝謝

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容