1import preferences from'@ohos.data.preferences'23exportclassUser{4 name?:string5 age?:number6}78exportclassUserStore{9KEY='user-store'1011getStore(){12return preferences.getPreferences(getContext(this),'userStore')13}1415asyncsetData(data: User){16const store =awaitthis.getStore()17await store.put(this.KEY,JSON.stringify(data))18await store.flush()19}2021asyncgetData(){22const store =awaitthis.getStore()23const data =await store.get(this.KEY,'{}')asstring24returnJSON.parse(data)as User
25}2627asyncdelData(){28const store =awaitthis.getStore()29await store.delete(this.KEY)30await store.flush()31}3233}
pages/Index.ets
1import router from'@ohos.router'2import{ User, UserStore }from'../utils/userStore'34@Entry5@Component6struct Index {7 userStore: UserStore
8@State9 user: User ={}1011aboutToAppear(){12this.userStore =newUserStore()13this.getUser()14}1516asyncgetUser(){17const user =awaitthis.userStore.getData()18this.user = user
19}2021build(){22Column({ space:15}){2324if(this.user?.name &&this.user?.age ){25Text(`${this.user.name } 今年 ${this.user.age } 岁`)26}2728Button('设置 User')29.onClick(async()=>{30awaitthis.userStore.setData({ name:'jack', age:18})31awaitthis.getUser()32})3334Button('修改 User')35.onClick(async()=>{36awaitthis.userStore.setData({ name:'tom', age:17})37awaitthis.getUser()38})3940Button('删除 User')41.onClick(async()=>{42awaitthis.userStore.delData()43awaitthis.getUser()44})4546Button('换一页')47.onClick(()=>{48 router.pushUrl({49 url:'pages/DetailPage'50})51})52}53.height('100%')54.width('100%')55.justifyContent(FlexAlign.Center)56}57}