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

arkts首选项,相关代码封装,直接调用即可

先创建一个 chanku.ets文件,装封闭好的文件写入,内容如下:

//首选项库封闭模块,调用此模块,就可以用一句代码来读取或写入数据
import { preferences } from '@kit.ArkData'

export class ChanKuClass {
  //默认的仓库名称
  static mo_store: string = 'mo_store'
  static mo_key: string = 'mo_key'
  static mo_value: string = 'mo_value'

  //创建仓库:没有就新建,有了就获取,源码来自 wb98.com
  static getStore(context: Context, storeName: string) {
    const store = preferences.getPreferencesSync(context, {
      name: storeName || ChanKuClass.mo_store
    })
    return store
  }

  //仓库中添加数据
  static async setToken(context: Context, storeName: string, key: string, value: string) {
    //获取创建的仓库
    const store = ChanKuClass.getStore(context, storeName)
    //添加数据:键,值
    // await store.put(key || ChanKuClass.mo_key, value || ChanKuClass.mo_value)
    await store.putSync(key || ChanKuClass.mo_key, value)
    //将数据写入磁盘
    await store.flush()
  }

  //获得仓库中的数据
  static getToken(context: Context, storeName: string, key: string) {
    const store = ChanKuClass.getStore(context, storeName)
    const tokey = store.getSync(key, '')
    return tokey
  }
}


下面是调用上述文件,来读取和写入设置值的代码:

import { ChanKuClass } from './chanku';

//此模块是首选项演示--源码来自 wb98.com
@Entry
@Component
struct Page12 {
  @State txt1: string = '30'

  build() {
    Column({ space: 20 }) {
      Text('在下面输入要设置的值')
        .fontSize(20)
        .fontWeight(700)
      TextInput({ placeholder: '请输入数字', text: '30' })
        .type(InputType.Number)
        .backgroundColor(Color.Pink)
        .width(200)
        .onChange((value) => {
          this.txt1 = value
        })
      Button('写入')
        .onClick(() => {
          ChanKuClass.setToken(getContext(), 'set1', 'fontdx', this.txt1)// 仓库名,键名,值
        })
      Button('读出')
        .onClick(() => {
          const xx = ChanKuClass.getToken(getContext(), 'set1', 'fontdx')//仓库名,键名
          AlertDialog.show({
            message: '读出结果:' + xx
          })
        })

    }
    .height('100%')
    .width('100%')
  }
}

不要忘记,测试时,要用真机或模拟器来测试。

打赏 支付宝打赏 微信打赏

来源:济亨网

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

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

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