当前位置:首页 » 程序代码 » 正文

首选项存储:存值,永存,取值,删值 arkts

真机,模拟器,预览器,测试下面的代码。 川石,asrkts,鸿蒙

import { BusinessError } from '@kit.BasicServicesKit'
import { preferences } from '@kit.ArkData'  //导入首选项模块

@Entry
@Component
struct Page8 {
  dataPreferences: preferences.Preferences | null = null  //Preferences实例-wb98.com
  @State fontSize: number = 25

  aboutToAppear(): void {
    let options: preferences.Options = { name: 'myStore' } //仓库名:myStore
    this.dataPreferences = preferences.getPreferencesSync(getContext(this), options) //获取Preferences实例
  }

  build() {

    Column({ space: 10 }) {
      Text("今天天气不错")
        .fontSize(this.fontSize)
        .margin({ bottom: 180 })
      Button('存值')
        .width('100%')
        .onClick(async () => {
          // this.dataPreferences?.put('fontSize', 45)
          this.dataPreferences?.put('fontSize', 45, (err: BusinessError) => {
            if (err) {
              console.error(`写入数据失败:code=${err.code},message=${err.message}`)
              return
            }
            console.log('写入数据成功')
          })
        })

      Button('永存')
        .width('100%')
        .backgroundColor(Color.Orange)
        .onClick(async () => {
          // this.dataPreferences?.flush()
          this.dataPreferences?.flush((err: BusinessError) => {
            if (err) {
              console.log(`存入数据失败:code=${err.code},message:${err.message}}`)
              return
            }
            console.log('存入数据成功')
          })
        })

      Button("取值")
        .width('100%')
        .onClick(() => {
          // this.dataPreferences?.get('fontSize', 25)
          this.dataPreferences?.get('fontSize', 25, (err: BusinessError, val:preferences.ValueType) => {
            if (err) {
              console.error(`获取数据失败:code=${err.code},message=${err.message}`)
              return
            }
            this.fontSize = parseInt(val.toString());
            console.log(`获取数据成功:val = ${val}`)
          })
        })

      Button('删值')
        .width('100%')
        .onClick(() => {
          // this.dataPreferences?.delete('fontSize')
          this.dataPreferences?.delete('fontSize', (err: BusinessError) => {
            if (err) {
              console.error(`删除失败: code = ${err.code},message =${err.message}`)
              return
            }
            console.log('删除成功')
          })
        })
    }
    .padding(10)
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
    .alignItems(HorizontalAlign.Center)

  }
}



打赏 支付宝打赏 微信打赏

来源:济亨网

本文链接:https://www.wb98.com/post/377.html

asrkts  鸿蒙  
    << 上一篇 下一篇 >>

    湘公网安备 43011102000514号 - 湘ICP备08100508号