程序员的知识教程库

网站首页 > 教程分享 正文

鸿蒙开发(七十四):页面级状态 LocalStorage

henian88 2024-09-17 21:25:35 教程分享 4 ℃ 0 评论

除了 @Provide/@Consume 可以跨组件传递数据外。

LocalStorage 也可以实现跨组件传递数据。

首先,我们在 Index.ets 页面上创建 LocalStorage 的实例。

/**
 * LocalStorage 实例
 */
const storage = new LocalStorage()

并在构造函数中初始化你要传递的数据,以 key/value 形式。

例如,{ name: "张三", age: 18 }。

/**
 * LocalStorage 实例
 */
const storage = new LocalStorage({ name: "张三", age: 18 })

然后,将 storage 传给 @Entry 装饰器。

/**
 * LocalStorage 实例
 */
const storage = new LocalStorage({ name: "张三", age: 18 })

@Entry(storage)
@Component
struct Index {
  build() {
  }
}

这一步的作用是将 LocalStorage 和页面进行绑定

接下来,我们就使用 LocalStorage 里面的值。

使用方式:@LocalStorageProp(key)/@LocalStorageLink(key)

  • LocalStorageProp 单向传递
  • LocalStorageLink 双向传递

Prop 和 Link 前面几章已经详细介绍过,这里就不再赘述了。

在 Index 组件里,定义一个 @LocalStorageLink(key) 装饰的变量 name,key 为“name”,类型要和 LocalStorage 里面的数据类型一样,并且该变量必须要设置默认值。

@Entry(storage)
@Component
struct Index {
  /**
   * 状态变量
   */
  @LocalStorageLink("name") name: string = "Index"

  build() {
  }
}

然后,在 build 函数里显示 name,并通过点击按钮修改 name 的值。ItemA 是一个子组件。

@Entry(storage)
@Component
struct Index {
  /**
   * 状态变量
   */
  @LocalStorageLink("name") name: string = "Index"

  build() {
    Column() {
      Text(this.name)
      Button("Index按钮")
        .onClick(() => {
          this.name = "Index更新"
        })

      ItemA()
    }
    .width('100%')
  }
}

ItemA 组件里使用 ItemB 子组件:

@Component
struct ItemA {
  build() {
    ItemB()
  }
}

在 ItemB 组件里定义一个 @LocalStorageLink(key) 装饰的变量 name,key 为“name”,变量类型要和 LocalStorage 里定义的一样,变量还要有默认值:

@Component
struct ItemB {
  /**
   * 状态变量
   */
  @LocalStorageLink("name") name: string = "ItemB"

  build() {
    Column() {
      Text(this.name)
      Button("ItemB按钮")
        .onClick(() => {
          this.name = "ItemB更新"
        })
    }
  }
}

完整代码:

/**
 * LocalStorage 实例
 */
const storage = new LocalStorage({ name: "张三", age: 18 })

@Entry(storage)
@Component
struct Index {
  /**
   * 状态变量
   */
  @LocalStorageLink("name") name: string = "Index"

  build() {
    Column() {
      Text(this.name)
      Button("Index按钮")
        .onClick(() => {
          this.name = "Index更新"
        })

      ItemA()
    }
    .width('100%')
  }
}

@Component
struct ItemA {
  build() {
    ItemB()
  }
}

@Component
struct ItemB {
  /**
   * 状态变量
   */
  @LocalStorageLink("name") name: string = "ItemB"

  build() {
    Column() {
      Text(this.name)
      Button("ItemB按钮")
        .onClick(() => {
          this.name = "ItemB更新"
        })
    }
  }
}

运行结果:

从运行结果来看,修改 Index 组件中 name 的值,Index 和 ItemB 组件的UI刷新。

修改 ItemB 组件中 name 的值,Index 和 ItemB 组件的UI也会刷新。

总结

  • 创建 LocalStorage 实例,并在构造函数完成初始化操作。
  • 将 LocalStorage 与 @Entry 装饰器进行绑定。
  • 使用 @LocalStorageProp/@LocalStorageLink 装饰需要同步的变量,变量必须初始化。

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表