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

然后点击按钮

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

相关推荐
用户294694054481610 小时前
DSH Desktop - Electron on HarmonyOS Edition
harmonyos·deepseek
IsITGirl11 小时前
HarmonyOS 鸿蒙 WuKong 稳定性测试报错 Failed to connect to AAMS(已解决)
华为·harmonyos
万物智能信息科技13 小时前
鸿蒙RS232驱动开发—【万物智能之开源鸿蒙OpenHarmony系统实战开发系列教程】
驱动开发·华为·开源·harmonyos·鸿蒙
less_1213815 小时前
鸿蒙 WPS Open SDK 接入指南:凭据申请、HAR 集成与 registerApp 校验
华为·harmonyos·wps
威哥爱编程1 天前
HarmonyOS 7 Agent 开发实战 07:多 Agent 任务分解与反思
agent·harmonyos
威哥爱编程1 天前
HarmonyOS 7 Agent 开发实战 06:Agent 记忆与上下文管理
agent·harmonyos
HarmonyOS_SDK1 天前
【HarmonyOS SDK Skills】扫码能力一键构建,系统级高精度扫码秒实现
harmonyos
结局无敌2 天前
React Native for OpenHarmony 实战:三方库 react-native-modal-dialog 的鸿蒙化适配指南
深度学习·算法·react native·react.js·harmonyos
hunterandroid2 天前
HarmonyOS 长列表滚动性能优化:预渲染、离屏缓存与 GPU 合成策略
华为·前端框架
结局无敌2 天前
React Native for OpenHarmony 实战:三方库 react-native-paper 的鸿蒙化适配指南
javascript·人工智能·深度学习·react native·react.js·ecmascript·harmonyos