美文网首页
鸿蒙~AppStorage中对应的属性建立双向或单向同步

鸿蒙~AppStorage中对应的属性建立双向或单向同步

作者: 胡修波 | 来源:发表于2024-01-10 07:59 被阅读0次
    • 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 */
          })
        }
      }
    }
    

    相关文章

      网友评论

          本文标题:鸿蒙~AppStorage中对应的属性建立双向或单向同步

          本文链接:https://www.haomeiwen.com/subject/qzzandtx.html