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组件

然后点击按钮

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

相关推荐
麟听科技14 小时前
HarmonyOS 6.0+ APP智能种植监测系统开发实战:农业传感器联动与AI种植指导落地
人工智能·分布式·学习·华为·harmonyos
前端不太难15 小时前
HarmonyOS PC 焦点系统重建
华为·状态模式·harmonyos
SpringSir15 小时前
鸿蒙 文字右侧的小红点
鸿蒙
空白诗15 小时前
基础入门 Flutter for Harmony:Text 组件详解
javascript·flutter·harmonyos
lbb 小魔仙16 小时前
【HarmonyOS】React Native实战+Popover内容自适应
react native·华为·harmonyos
motosheep17 小时前
鸿蒙开发(四)播放 Lottie 动画实战(Canvas 渲染 + 资源加载踩坑总结)
华为·harmonyos
左手厨刀右手茼蒿17 小时前
Flutter for OpenHarmony 实战:Barcode — 纯 Dart 条形码与二维码生成全指南
android·flutter·ui·华为·harmonyos
lbb 小魔仙17 小时前
【HarmonyOS】React Native of HarmonyOS实战:手势组合与协同
react native·华为·harmonyos
果粒蹬i18 小时前
【HarmonyOS】React Native实战项目+NativeStack原生导航
react native·华为·harmonyos
waeng_luo19 小时前
HarmonyOS 应用开发 Skills
华为·harmonyos