鸿蒙开发:浅入AppStorageV2: 应用全局UI状态存储

44 阅读1分钟

🎯V2: 浅入AppStorageV2: 应用全局UI状态存储

⭐⭐⭐

📌 见解

1️⃣ AppStorage与AppStorageV2之间的数据不互通

2️⃣ AppStorageV2支持在主线程内多个UIAbility实例间的状态共享

3️⃣ 操作同一个key,connect方法传入不同的类型会导致应用异常,需要保证传入的类型与之前传入的一致

⚠️ 使用场景

AppStorageV2应用级共享数据使用connect方法实现对AppStorageV2中数据的修改和同步

🧩 拆解

import { AppStorageV2, promptAction, router } from '@kit.ArkUI'
import { modelAll } from '../modelAll/modelAll'


/**
 * connect:创建或获取储存的数据
 *
 * remove:删除指定key的储存数据
 *
 * keys:返回所有AppStorageV2中的key
 */

// 子页面
@Entry
@ComponentV2
export struct AppStorageV2Son {
  @Local prop: modelAll = AppStorageV2.connect(modelAll, () => new modelAll())!

  build() {
    Column({ space: 10 }) {
      Text(this.prop.p1.toString())

      Button('改变modelAll下的p1数据').onClick((event: ClickEvent) => {
        this.prop.p1 = 10000000
      })

      Button('删除指定数据').onClick((event: ClickEvent) => {
        this.prop.p1 = 0
        AppStorageV2.remove(modelAll)
      })

      Button('返回所有AppStorageV2,key').onClick((event: ClickEvent) => {
        promptAction.showToast({ message: `${AppStorageV2.keys()}` })
      })


      Button('跳转').onClick((event: ClickEvent) => {
        router.pushUrl({ url: 'otherDir/AppStorageV2SonPage' })
      })
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}


import { AppStorageV2, router } from '@kit.ArkUI'
import { modelAll } from '../modelAll/modelAll'
// 父页面
@Entry
@ComponentV2
export struct AppStorageV2SonPage {
  @Local prop: modelAll = AppStorageV2.connect(modelAll, () => new modelAll())!

  build() {
    Column({ space: 10 }) {
      Text(this.prop.p1.toString())

      Button('返回').onClick((event: ClickEvent) => {
        router.pushUrl({ url: 'otherDir/AppStorageV2' })
      })
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}

@ObservedV2
export class modelAll {
  @Trace p1: number = 0
  @Trace p2: number = 10
}

📝 AppStorageV2拥有应用级全局共享数据的能力,可以通过connect方法对指定的key进行curd, 跨UIAbility的数据共享

🌸🌼🌺