- AppStorage是LocalStorage的单例对象,ArkUI在应用程序启动时创建该对象,在页面中使用@StorageLink和@StorageProp为多个页面之间共享数据
- 也可以使用PersistentStorage将AppStorage中的特定属性持久化到本地磁盘的文件中,再次启动的时候@StorageLink和@StorageProp会恢复上次应用退出的数据
@Component
struct LinkLinkChild {
@StorageLink("testNum") @Watch("testNumChange") testNum: number = 1;
testNumChange(propName: string): void {
console.log(`LinkLinkChild: testNum value ${this.testNum}`);
}
build() {
Text(`LinkLinkChild: ${this.testNum}`)
}
}
@Component
struct PropLinkChild {
@StorageProp("testNum") @Watch("testNumChange") testNumGrand: number = 1;
testNumChange(propName: string): void {
console.log(`PropLinkChild: testNumGrand value ${this.testNumGrand}`);
}
build() {
Text(`PropLinkChild: ${this.testNumGrand}`)
.height(70)
.backgroundColor(Color.Red)
.onClick(() => {
this.testNumGrand += 1;
})
}
}
@Component
struct Sibling {
@StorageLink("testNum") @Watch("testNumChange") testNum: number = 1;
testNumChange(propName: string): void {
console.log(`Sibling: testNumChange value ${this.testNum}`);
}
build() {
Text(`Sibling: ${this.testNum}`)
}
}
@Component
struct LinkChild {
@StorageLink("testNum") @Watch("testNumChange") testNum: number = 1;
testNumChange(propName: string): void {
console.log(`LinkChild: testNumChange value ${this.testNum}`);
}
build() {
Column() {
Button('incr testNum')
.onClick(() => {
console.log(`LinkChild: before value change value ${this.testNum}`);
this.testNum = this.testNum + 1
console.log(`LinkChild: after value change value ${this.testNum}`);
})
Text(`LinkChild: ${this.testNum}`)
LinkLinkChild({ /* empty */
})
PropLinkChild({ /* empty */
})
}
.height(200).width(200)
}
}
@Entry
@Component
struct Parent {
@StorageLink("testNum") @Watch("testNumChange1") testNum: number = 1;
testNumChange1(propName: string): void {
console.log(`Parent: testNumChange value ${this.testNum}`)
}
build() {
Column() {
LinkChild({ /* empty */
})
Sibling({ /* empty */
})
}
}
}
网友评论