鸿蒙笔记--存储

    这一节了解一下鸿蒙中常用存储API,主要有LocalStorage ,AppStorage,PersistentStorage,LocalStorage 是一种页面级UI状态存储机制,主要用于在UIAbility内和页面间共享状态数据。通过使用特定的装饰器,LocalStorage能够实现组件内部变量与LocalStorage中属性的单向或双向同步。

LocalStorage的装饰器器
@LocalStorageProp:此装饰器用于建立组件内部变量与LocalStorage中指定属性的单向同步关系。当LocalStorage中的属性变化时,会同步到组件的变量,但本地修改不会同步回LocalStorage。
@LocalStorageLink:此装饰器用于建立组件内部变量与LocalStorage中指定属性的双向同步关系。本地和LocalStorage中的修改都会互相同步。

栗子:

EntryAbility.ts 

import UIAbility from '@ohos.app.ability.UIAbility';
import hilog from '@ohos.hilog';
import window from '@ohos.window';

export default class EntryAbility extends UIAbility {
  onCreate(want, launchParam) {
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
  }

  onDestroy() {
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onDestroy');
  }

  storage = new LocalStorage({
    user: {
      name: 'jack',
      age: 20
    }
  })

  onWindowStageCreate(windowStage: window.WindowStage) {
    // Main window is created, set main page for this ability
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');

    windowStage.loadContent('pages/Index', this.storage, (err, data) => {
      if (err.code) {
        hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
        return;
      }
      hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');
    });
  }

  onWindowStageDestroy() {
    // Main window is destroyed, release UI related resources
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageDestroy');
  }

  onForeground() {
    // Ability has brought to foreground
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground');
  }

  onBackground() {
    // Ability has back to background
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onBackground');
  }
}

Index.ets

import { User } from '../models'

const storage = LocalStorage.GetShared()

@Entry(storage)
@Component
struct Index {

  @LocalStorageProp('user')
  user: User = {}

  build() {
    Column({ space: 30 }) {
      Text(this.user.name + this.user.age)
        .onClick(() => {
          this.user.age ++
        })

      Child()

      Navigator({
        target: 'pages/OtherPage',
      }){
        Text('Jump Other Page')
      }
    }
    .height('100%')
  }
}

@Component
struct Child {

  @LocalStorageLink('user')
  user: User = {}

  build() {
    Text(this.user.name + this.user.age)
      .onClick(() => {
        this.user.age ++
      })
  }
}

OtherPage.ets 

import { User } from '../models'

const storage = LocalStorage.GetShared()

@Entry(storage)
@Component
struct OtherPage {

  @LocalStorageLink('user')
  user: User = {}

  build() {
    Column(){
      Text(' Other Page ')
      Text(this.user.name + this.user.age)
        .onClick(() => {
          this.user.age ++
        })
    }
  }
}

bean类:

Index.ets

export class User {
  name?: string
  age?: number
}

AppStorage为应用程序的UI状态属性提供中央存储,并且由UI框架在应用程序启动时创建。与LocalStorage不同,LocalStorage是页面级的存储,通常用于单个页面或页面间的数据共享,而AppStorage则是全局的状态共享,相当于整个应用的“中枢”。

AppStorage的装饰器
@StorageProp:此装饰器用于建立组件内部变量与AppStorage中指定属性的单向同步关系。当AppStorage中的属性变化时,会同步到组件的变量,但本地修改不会同步回AppStorage。
@StorageLink:此装饰器用于建立组件内部变量与AppStorage中指定属性的双向同步关系。本地和AppStorage中的修改都会互相同步。

栗子:

Index.ets

import promptAction from '@ohos.promptAction'
import { User } from '../models'
AppStorage.SetOrCreate('user', { name: 'jack', age: 16 })

@Entry
@Component
struct Index {

  @StorageLink('user')
  user: User = {}

  build() {
    Column({ space: 15 }) {
      Text(this.user.name + this.user.age)
        .onClick(() => {
          this.user.age ++
        })

      Divider()
      Child()
      Divider()
      ChildB()
    }
    .height('100%')
    .width('100%')
    .justifyContent(FlexAlign.Center)
  }
}

@Component
struct Child {

  @StorageLink('user')
  user: User = {}

  build() {
    Text(this.user.name + this.user.age)
      .onClick(() => {
        this.user.age ++
      })
  }
}

@Component
struct ChildB {

  build() {
    Column(){
      Text('获取 AppStorage')
        .onClick(() => {
          const user = AppStorage.Get<User>('user')
          promptAction.showToast({ message: user.name + user.age })
        })
      Text('修改 AppStorage')
        .onClick(() => {
          AppStorage.Set<User>('user', { name: 'tom', age: 20 })
        })

      Text('Link 修改 AppStorage')
        .onClick(() => {
          const link: SubscribedAbstractProperty<User> = AppStorage.Link('user')
          // promptAction.showToast({ message: link.get().name + link.get().age })
          link.set({
            name: link.get().name,
            age: link.get().age + 1
          })
        })
    }
  }
}

         PersistentStorage 是一个用于实现数据持久化的存储机制,其主要作用是确保选定的 AppStorage 属性在应用程序重新启动时的值与应用程序关闭时的值相同。PersistentStorage 将选定的 AppStorage 属性保留在设备磁盘上,通过 API 来决定哪些 AppStorage 属性应借助 PersistentStorage 进行持久化。所有属性访问都是对 AppStorage 的访问,AppStorage 中的更改会自动同步到 PersistentStorage。

PersistentStorage的装饰器
@persistProp:此装饰器用于将指定的 AppStorage 属性持久化到设备磁盘上。例如,使用 PersistentStorage.persistProp('aProp', 47) 将 'aProp' 属性持久化。
@StorageLink:此装饰器用于建立组件内部变量与 AppStorage 中指定属性的双向同步关系,所有同步也会反映到 PersistentStorage 中。

栗子:

Index.ets

import { User } from '../models'
PersistentStorage.PersistProp('count', 100)
PersistentStorage.PersistProp('user', `{ "name": "jack", "age": 17 }`)

@Entry
@Component
struct Index {
  @StorageLink('count')
  count: number = 0
  @StorageLink('user')
  userJson: string = ''

  @State
  user: User = JSON.parse(this.userJson)

  build() {
    Column({ space: 15 }) {

      Text(this.count.toString())
        .onClick(() => {
          this.count ++
        })

      Text(this.user.name + this.user.age)
        .onClick(() => {
          this.user.age ++
          // this.userJson = JSON.stringify(this.user)
          AppStorage.Set('user', JSON.stringify(this.user))
        })
      Divider()
      ChildA()
    }
    .height('100%')
    .width('100%')
    .justifyContent(FlexAlign.Center)
  }
}

@Component
struct ChildA {
  @StorageLink('count')
  count: number = 0
  @StorageLink('user')
  userJson: string = ''

  build() {
    Column(){
      Text(this.count.toString())
        .onClick(() => {
          this.count ++
        })
      Text(this.userJson)
    }
  }
}

相关推荐

  1. 鸿蒙笔记--存储

    2024-07-22 17:48:04       16 阅读
  2. 鸿蒙 状态管理-应用存储

    2024-07-22 17:48:04       35 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-22 17:48:04       52 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-22 17:48:04       54 阅读
  3. 在Django里面运行非项目文件

    2024-07-22 17:48:04       45 阅读
  4. Python语言-面向对象

    2024-07-22 17:48:04       55 阅读

热门阅读

  1. Github订阅地址

    2024-07-22 17:48:04       15 阅读
  2. Qt:愚蠢的qmake

    2024-07-22 17:48:04       21 阅读
  3. 《设计模式之美》读书笔记2

    2024-07-22 17:48:04       16 阅读
  4. Seata 面试题及答案整理,最新面试题

    2024-07-22 17:48:04       19 阅读
  5. Linux 防火墙配置【iptable,firewalld,ufw】

    2024-07-22 17:48:04       17 阅读
  6. Redisson内置延迟队列RDelayedQueue

    2024-07-22 17:48:04       17 阅读
  7. MYSQL设计和开发规范(简易版)

    2024-07-22 17:48:04       18 阅读
  8. 解决MySQL中LIMIT大偏移量加载慢的问题

    2024-07-22 17:48:04       15 阅读