浅入PersistenceV2: 持久化储存UI状态
·
🎯V2: 浅入PersistenceV2: 持久化储存UI状态
⭐⭐⭐
📌 见解
1️⃣ PersistenceV2存储的类型每次@Trace变更会自动触发磁盘写入
| 特性 | globalConnect | connect |
|---|---|---|
| 存储路径 | 应用级别(全局共享) | Module级别(隔离存储) |
| 使用场景 | 跨Module/跨Ability的数据共享 | 同一Module内数据隔离 |
| 兼容性 | 从API version 18开始支持 | 从API version 12开始支持 |
⚠️ 使用场景
在两个页面之间存储数据,使用globalConnect存储数据全局共享
🧩 拆解
import { PersistenceV2 } from '@kit.ArkUI';
// 接受序列化失败的回调
PersistenceV2.notifyOnError((key: string, reason: string, msg: string) => {
console.error(`error key: ${key}, reason: ${reason}, message: ${msg}`)
});
/**
* 为了增强状态管理框架对持久化存储UI的能力,开发者可以使用PersistenceV2存储持久化的数据。
*
* PersistenceV2提供状态变量持久化能力,开发者可以通过connect绑定同一个key,在状态变量变换和应用冷启动时,实现持久化能力。
*
* PersistenceV2可以使用globalConnect存储数据跨Module/跨Ability的数据共享
*/
@Entry
@ComponentV2
struct PersistenceV2Case {
@Local prop: modelAll = new modelAll()
build() {
Column() {
Button('点击:connect')
.onClick(() => {
// TODO: connect
// this.prop = PersistenceV2.connect(modelAll, 'Sample', () => new modelAll())!
// TODO: globalConnect
this.prop = PersistenceV2.globalConnect({ type: modelAll, defaultCreator: () => new modelAll() })!
})
Button('点击:remove')
.onClick(() => PersistenceV2.remove(modelAll))
Button('点击:save')
.onClick(() => PersistenceV2.save(modelAll))
Text(`Page1 add 1 to prop.p1: ${this.prop.p1}`)
.fontSize(30)
.onClick(() => this.prop.p1++)
Text(`Page1 add 1 to prop.p2: ${this.prop.p1}`)
.fontSize(30)
.onClick(() => this.prop.p1++)
// 获取当前PersistenceV2里面的所有key
Text(`all keys in PersistenceV2: ${PersistenceV2.keys()}`)
.fontSize(30)
}
}
}
@ObservedV2
export class modelAll {
@Trace p1: number = 0
@Trace p2: number = 10
}
📝 PersistenceV2不仅可以模块数据隔离,还可以跨模块和Ability的数据共享
🌸🌼🌺
更多推荐



所有评论(0)