赞
踩
官方文档:通过用户首选项
实现数据持久化
import { common } from '@kit.AbilityKit'; import dataPreferences from '@ohos.data.preferences'; @Entry @Component struct Index { @State changeFontSize: number = 16; // 上下文 private context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext //1. 获取preference private preferencesInstance: dataPreferences.Preferences = dataPreferences.getPreferencesSync(this.context, { name: 'myStore' }); aboutToAppear(): void { //4. 页面打开后,直接从preference中获取上一次的数据 let result = this.preferencesInstance.getSync("fontSizeKey", 16) this.changeFontSize = Number(result) } build() { Column() { Row({ space: 10 }) { Text('当前进度一览').fontSize(this.changeFontSize) }.margin(20) Slider({ value: this.changeFontSize, min: 14, max: 22, step: 2, style: SliderStyle.InSet }) .showSteps(true) .width('75%') .onChange(async (value: number) => { this.changeFontSize = value //2. 保存数据 this.preferencesInstance.putSync('fontSizeKey', this.changeFontSize); //3. 持久化数据 this.preferencesInstance.flush() }) }.backgroundColor('#f2f3f5').width('100%').height('100%') } }
import dataPreferences from '@ohos.data.preferences'; import { common } from '@kit.AbilityKit'; @Entry @Component struct Index_preferences2 { @State message: string = 'Hello World'; private context:common.UIAbilityContext = getContext(this) as common.UIAbilityContext private preferencesInstance: dataPreferences.Preferences = dataPreferences.getPreferencesSync(this.context, { name: 'myStore' }); aboutToAppear(): void { let result = this.preferencesInstance.getSync("messageKey","默认值1") this.message = String(result) } build() { Row() { Column() { TextInput({text:this.message}).fontSize(20).fontWeight(FontWeight.Bold) .onChange((value)=>{ this.message = value }) Button("保存") .onClick(()=>{ this.preferencesInstance.putSync('message', this.message); this.preferencesInstance.flush() AlertDialog.show({message:"保存成功"}) }) Button("读取").onClick(() => { let result = this.preferencesInstance.getSync("messageKey","默认值2") this.message = String(result)//获取到的数据不是String,需要转换一下 AlertDialog.show({message:this.message}) console.log("test",result) }) } .width('100%') } .height('100%') } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。