HarmonyOS 路由传参

本文 我们来说两个page界面间的数据传递

路由跳转 router.pushUrl 之前我们用了不少了 但是我们只用了它的第一个参数 url

其实他还有个params参数

我们第一个组件可以编写代码如下

typescript 复制代码
import router from '@ohos.router'
@Entry
@Component
struct Index {

  build() {
    Row() {
      Column() {
        Button("跳转").onClick(()=>{
          router.pushUrl({
            url: "pages/AppView",
            params: {
              name: "小猫猫",
              age: 20
            }
          })
        })
      }
      .width('100%')
    }
    .height('100%')
  }
}

这里 我们button按钮设置点击事件 调用 router.pushUrl 跳转向 pages/AppView 页面

然后第二个参数 params 是一个对象 键值对 就是我们要传递给下一个界面的参数

我们第二个界面这样写

typescript 复制代码
import router from '@ohos.router'

let name:string = router.getParams()["name"]
let age:number = router.getParams()["age"]

@Entry
@Component
struct AppView {
  build() {
    Row() {
      Column(){
        Text(name)
        Text(""+age)
      }
      .width('100%')
    }
    .height('100%')
  }
}

通过 router.getParams 就可以取到上一个界面传过来的值 然后 后面一对数组括号 告诉它你要取哪个字段

然后 我们用text组件展示内容 因为text 不能用数字 所以我们要用 字符串加的方式 将age转存字符串类型的

我们开启预览模式 运行index组件

然后点击按钮

跳转后 第二个界面也就顺利的拿到了传过来的参数

相关推荐
u***j32414 分钟前
HarmonyOS分布式能力核心技术深度解析
分布式·华为·harmonyos
7***n7519 分钟前
HarmonyOS分布式数据管理
分布式·华为·harmonyos
S***y3961 小时前
HarmonyOS在智能家居中的情景模式
华为·智能家居·harmonyos
IT充电站1 小时前
HarmonyOS 帧动画 animator
harmonyos
IT充电站1 小时前
HarmonyOS 位置服务全攻略:精准定位、地理编码与后台持续定位实现
harmonyos
IT充电站1 小时前
HarmonyOS 组件导航(Navigation)
harmonyos
6***37941 小时前
HarmonyOS在智能家居中的场景联动
华为·智能家居·harmonyos
u***u6852 小时前
HarmonyOS在智能手表中的开发
华为·harmonyos·智能手表
0***143 小时前
HarmonyOS系统安全机制
华为·harmonyos
m***D2864 小时前
HarmonyOS在智能家居中的家庭网络
华为·智能家居·harmonyos