当前位置:   article > 正文

HarmonyOS 通过AppStorage定义组件共享数据_appstorage setorcreate

appstorage setorcreate

我们实现组件间共享数据可以通过 AppStorage
他下面有两个函数可以实现这一功能
SetOrCreate和Set

AppStorage.SetOrCreate("dataMap",{
    name:"小猫猫"
})
AppStorage.Set("dataMap",{
    name:"小猫猫"
})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

Set是 如果键值存在 他会覆盖 但是 如果键值不存在 就会赋值不上
SetOrCreate则是 如果没有就赋值 如果有了 就修改

所以这里我们肯定选择更安全的 SetOrCreate
然后 我们可以通过 AppStorage.Get(“键名”) 获取数据

这里 我们可以写一个案例
index组件代码如下

import router from '@ohos.router'
@Entry
@Component
struct Index {

  build() {
    Row() {
      Column() {
        Button("赋值").onClick(()=>{
          AppStorage.SetOrCreate("dataMap",{
            name:"小猫猫"
          })
          router.pushUrl({
            url: "pages/AppView",
            params: {
              name: "小猫猫",
              age: 20
            }
          })
        })
      }
      .width('100%')
    }
    .height('100%')
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

我们设置了一个button按钮 点击时 用 AppStorage.SetOrCreate 存入一个键值对
键为 dataMap 值为一个对象 里面有一个name字段 值为 小猫猫

然后 跳转向 AppView

AppView 编写代码如下

@Entry
@Component
struct AppView {
  build() {
    Row() {
      Column(){
        Button("获取").onClick(()=>{
          let data:object = AppStorage.Get("dataMap")
          // @ts-ignore
          console.log(data.name);
        })
      }
      .width('100%')
    }
    .height('100%')
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

这里 我们定义了一个data 类型为object 通过 AppStorage.Get 获取键为 dataMap的值
然后 用 console.log将对象的 name字段输出在控制台上

我们index组件 开启预览器 点击这里赋值 并且跳转向下一个界面
在这里插入图片描述
到了第二个界面 点击获取 控制台输出明显就是拿到了
在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/299107
推荐阅读
相关标签
  

闽ICP备14008679号