鸿蒙应用开发-应用状态存储(LocalStorage、AppStorage..)

1. UIAbility内状态-LocalStorage

LocalStorage 是页面级的UI状态存储,通过 @Entry 装饰器接收的参数可以在页面内共享同一个 LocalStorage 实例。 LocalStorage 也可以在 UIAbility 内,页面间共享状态。

1)页面内共享

  • 创建 LocalStorage 实例:const storage = new LocalStorage({ key: value })
  • 单向 @LocalStorageProp('user') 组件内可变
  • 双向 @LocalStorageLink('user') 全局均可变
ts 复制代码
class User {
  name?: string
  age?: number
}
const storage = new LocalStorage({
  user: { name: 'jack', age: 18 }
})

@Entry(storage)
@Component
struct Index {
  @LocalStorageProp('user')
  user: User = {}

  build() {
    Column({ space: 15 }){
      Text('Index:')
      Text(this.user.name + this.user.age)
      Divider()
      ChildA()
      Divider()
      ChildB()
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}

@Component
struct ChildA {
  @LocalStorageProp('user')
  user: User = {}

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

@Component
struct ChildB {
  @LocalStorageLink('user')
  user: User = {}

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

2)页面间共享

  • UIAbility 创建 LocalStorage 通过 loadContent 提供给加载的窗口

在页面使用 const storage = LocalStorage.GetShared() 得到实例,通过 @Entry(storage) 传入页面

entryAbility/EntryAbility.ts

ts 复制代码
+  storage = new LocalStorage({
+    user: { name: 'jack', age: 18 }
+  })

  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) ?? '');
    });
  }

models/index.ets

ts 复制代码
export class User {
  name?: string
  age?: number
}

pages/Index.ets

ts 复制代码
import { User } from '../models'
const storage = LocalStorage.GetShared()

@Entry(storage)
@Component
struct Index {
  @LocalStorageProp('user')
  user: User = {}

  build() {
    Column({ space: 15 }) {
      Text('Index:')
      Text(this.user.name + this.user.age)
        .onClick(()=>{
          this.user.age ++
        })
      Navigator({ target: 'pages/OtherPage' }){
        Text('Go Other Page')
      }
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}

pages/OtherPage.ets

ts 复制代码
import { User } from '../models'
const storage = LocalStorage.GetShared()

@Entry(storage)
@Component
struct OtherPage {
  @LocalStorageLink('user')
  user: User = {}

  build() {
    Column({ space: 15 }) {
      Text('OtherPage:')
      Text(this.user.name + this.user.age)
        .onClick(()=>{
          this.user.age ++
        })
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}

注意

  • 页面间共享需要要模拟器测试
  • 应用逻辑中使用参考 链接

2. 应用状态-AppStorage

AppStorage 是应用全局的UI状态存储,是和应用的进程绑定的,由UI框架在应用程序启动时创建,为应用程序UI状态属性提供中央存储。

如果是初始化使用 AppStorage.SetOrCreate(key,value)

单向 @StorageProp('user') 组件内可变

双向 @StorageLink('user') 全局均可变

1)通过UI装饰器使用

ts 复制代码
import { User } from '../models'

AppStorage.SetOrCreate<User>('user', { name: 'jack', age: 18 })

@Entry
@Component
struct Index {
  @StorageProp('user')
  // 可忽略,编辑器类型错误
  user: User = {}

  build() {
    Column({ space: 15 }) {
      Text('Index:')
      Text(this.user.name + this.user.age)
        .onClick(() => {
          this.user.age++
        })
      Divider()
      ChildA()
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}

@Component
struct ChildA {
  @StorageLink('user')
  user: User = {}

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

2)通过逻辑使用

  • AppStorage.Get<ValueType>(key) 获取数据
  • AppStorage.Set<ValueType>(key,value) 覆盖数据
  • const link: SubscribedAbstractProperty<ValueType> = AppStorage.Link(key)覆盖数据
    • link.set(value) 修改
    • link.get() 获取
ts 复制代码
import promptAction from '@ohos.promptAction'
import { User } from '../models'

AppStorage.SetOrCreate<User>('user', { name: 'jack', age: 18 })

@Entry
@Component
struct Index {
  @StorageLink('user')
  user: User = {}

  build() {
    Column({ space: 15 }) {
      Text('Index:')
      Text(this.user.name + this.user.age)
        .onClick(() => {
          this.user.age++
        })
      Divider()
      Text('Get()')
        .onClick(() => {
          // 仅获取
          const user = AppStorage.Get<User>('user')
          promptAction.showToast({
            message: JSON.stringify(user)
          })
        })
      Text('Set()')
        .onClick(() => {
          // 直接设置
          AppStorage.Set<User>('user', {
            name: 'tom',
            age: 100
          })
          // 观察页面更新没
        })
      Text('Link()')
        .onClick(() => {
          // 获取user的prop
          const user: SubscribedAbstractProperty<User> = AppStorage.Link('user')
          user.set({
            name: user.get().name,
            // 获取后修改
            age: user.get().age + 1
          })
        })
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}

3. 状态持久化-PersistentStorage

PersistentStorage 将选定的 AppStorage 属性保留在设备磁盘上。

DETAILS

UI和业务逻辑不直接访问 PersistentStorage 中的属性,所有属性访问都是对 AppStorage 的访问,AppStorage 中的更改会自动同步到 PersistentStorage

WARNING

  • 支持:number, string, boolean, enum 等简单类型;
  • 如果:要支持对象类型,可以转换成json字符串
  • 持久化变量最好是小于2kb的数据,如果开发者需要存储大量的数据,建议使用数据库api。

1)简单数据类型的持久化,和获取和修改

ts 复制代码
import { User } from '../models'

PersistentStorage.PersistProp('count', 100)

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

  build() {
    Column({ space: 15 }) {
      Text(this.count.toString())
        .onClick(() => {
          this.count++
        })
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}

2)复杂数据类型的持久化,和获取和修改

ts 复制代码
import promptAction from '@ohos.promptAction'
import { User } from '../models'

PersistentStorage.PersistProp('userJson', `{ "name": "jack", "age": 18 }`)

@Entry
@Component
struct Index {
  @StorageProp('userJson')
  @Watch('onUpdateUser')
  userJson: string = '{}'
  @State
  user: User = JSON.parse(this.userJson)

  onUpdateUser() {
    this.user = JSON.parse(this.userJson)
  }

  build() {
    Column({ space: 15 }) {
      Text('Index:')
      Text(this.user.name + this.user.age)
        .onClick(() => {
          this.user.age++
          // 修改
          AppStorage.Set('userJson', JSON.stringify(this.user))
        })
      Divider()
      Text('Get()')
        .onClick(() => {
          // 获取
          const user = AppStorage.Get<string>('userJson')
          promptAction.showToast({ message: user })
        })
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}

4. 设备环境-Environment

开发者如果需要应用程序运行的设备的环境参数,以此来作出不同的场景判断,比如多语言,暗黑模式等,需要用到Environment 设备环境查询。
Environment 的所有属性都是不可变的(即应用不可写入),所有的属性都是简单类型。
👀关注公众号:Android老皮!!!欢迎大家来找我探讨交流👀

相关推荐
Kevin Coding9 小时前
JsonConvert:适用于 Android、鸿蒙与 Flutter 的 JSON 转 Model 插件
android·flutter·harmonyos
m0_7496902311 小时前
【寻迹校园 HarmonyOS NEXT 实战 28】不交换手机号也能交接:固定校内交接点的隐私设计
华为·harmonyos·arkts·产品设计·隐私设计·安全交接
Magic-ZYJ11 小时前
HarmonyOS Stage 模型实战:UIAbility 生命周期如何驱动页面安全状态
安全·华为·harmonyos·鸿蒙·移动端开发·独立开发者·心晴手记
贾伟康11 小时前
【中国方言题库|09】HarmonyOS ArkTS 方言搜索实战:实现词语检索和无结果反馈
harmonyos·arkts·状态管理·arkui·本地搜索
Dovis(誓平步青云)12 小时前
从手机单栏到平板分栏:任务清单的筛选、选中态与不可变更新
华为·harmonyos
梦想不只是梦与想12 小时前
鸿蒙 AppGallery Connect:查看应用信息(三)
harmonyos·appgallery·client id·app id·developer id
贾伟康13 小时前
【中国方言题库|03】HarmonyOS ArkTS 四川话分库实战:复用题库组件并保持地区参数清晰
harmonyos·arkts·arkui·路由传参·组件复用
贾伟康13 小时前
【中国方言题库|10】HarmonyOS ArkTS 语音播放实战:管理读音播放与页面生命周期
生命周期·harmonyos·arkts·语音合成·texttospeech
YM52e1 天前
鸿蒙ArkTS实战项目 - 门店陈列巡检台:巡检卡片与多列切换实现
学习·华为·harmonyos
lilian2331 天前
Harmony os 技术实战|拼豆制图27:用单字符编码承载 50 张 70×70 图纸
前端·数据库·华为·harmonyos