利用 entryAbility 应用证明周期的特点,初始化 store 实例
import UIAbility from '@ohos.app.ability.UIAbility';
import hilog from '@ohos.hilog';
import window from '@ohos.window';
import dataPreferences from '@ohos.data.preferences';
export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) {
try{
dataPreferences.getPreferences(this.context,"myStore",(err,preferences)=>{
if(err){console.error("报错了");return}
/*使用 globalThis 方式可以让全局应用公用该属性*/
globalThis.entryAbilityPreferences = preferences;
})
}catch (error){
console.error("报错了")
}
}
}
封装 store 类,src\main\ets\utils\storage.ets
export default class Storage{
entryAbilityPreferences;
constructor() {
this.entryAbilityPreferences = globalThis.entryAbilityPreferences;
}
/*设置*/
setItem(key:string,value:string|number|boolean){
this.entryAbilityPreferences.has(key,(err, val)=>{
if(err){console.error("set调用失败");return}
if(val){console.error("key名已存在")}else{
try{
this.entryAbilityPreferences.put(key,value)
this.entryAbilityPreferences.flush()
}catch (err){
console.error("put方法报错了")
}
}
})
}
/*查找*/
getItem(key:string,defaultVal:string|number|boolean):Promise<string|number|boolean>{
return new Promise((resolve,reject)=>{
this.entryAbilityPreferences.get(key,defaultVal,(err,val)=>{
if(err){reject("报错了")}
resolve(val as string|number|boolean);
})
})
}
/*删除*/
delItem(key:string){
this.entryAbilityPreferences.delete(key)
}
}
使用
import router from '@ohos.router';
import promptAction from '@ohos.promptAction'
import Storage from "../utils/storage"
@Entry
@Component
struct Page {
storage = new Storage();
@Builder Header(){
Row(){
Button("存储")
.onclick(async ()=>{
this.storage.setItem("userName","龚箭") /*写入*/
let result = await this.storage.getItem("userName","登录") /*读取*/
})
}
}
}