HarmonyOS 鸿蒙Next中如何兼容router模块化调用与参数传递

HarmonyOS 鸿蒙Next中如何兼容router模块化调用与参数传递 如何正确使用router进行页面跳转并传递对象参数?

3 回复

兼容12以上的,推荐直接导入router模块。传递对象时,建议使用标准的JSON对象,避免复杂的原型链。 示例代码

import { router } from '@kit.ArkUI';

/**
 * @author J.query
 * @date 2024/10/22 11:07
 * @email j-query@foxmail.com
 * Description:
 */

// 定义用户信息接口
interface UserInfo {
  id: number;
  name: string;
  score: number;
}

// 定义路由参数接口
interface RouterParams {
  userInfo?: UserInfo;
}

// 导入模块

// 跳转函数
function navigateToDetail() {
  router.pushUrl({
    url: 'pages/Detail',
    params: {
      userInfo: {
        id: 1001,
        name: 'Test User',
        score: 95
      }
    }
  }).catch((err: Error) => {
    console.error('Navigation failed: ' + JSON.stringify(err));
  });
}

// 在目标页面 Detail.ets 接收
@Entry
@Component
struct DetailPage {
  @State userInfo: UserInfo = {id: 0, name: '', score: 0};

  aboutToAppear(): void {
    // 获取传递的参数
    const params = router.getParams() as  UserInfo ;
    if (params.name) {
      this.userInfo = params.name ? params : {id: 0, name: '', score: 0};
    }
  }

  build() {
    Column() {
      Text(`用户: ${this.userInfo.name}`)
      Text(`分数: ${this.userInfo.score}`)
    }.padding(20)
  }
}

cke_4820.png

效果图:页面跳转流畅,控制台无报错,正确显示传递的数据。

更多关于HarmonyOS 鸿蒙Next中如何兼容router模块化调用与参数传递的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在鸿蒙Next中,router模块化调用与参数传递通过router模块实现。使用router.pushUrl()进行页面跳转,参数以对象形式在params中传递。示例:router.pushUrl({url: 'pages/Page', params: {id: 1}}) 目标页面通过router.getParams()获取参数。模块化调用时,确保目标页面在module.json5中正确配置路由。参数支持基本类型与对象。

在HarmonyOS Next中,使用router进行模块化页面跳转并传递对象参数,核心是借助UIAbility上下文与want参数。对象参数需序列化后通过want传递,并在目标页面反序列化还原。

关键步骤:

  1. 参数传递方(发起跳转):

    • 将对象参数序列化为字符串(如使用JSON.stringify())。
    • 通过wantparameters属性携带参数。
    import { BusinessError } from '@ohos.base';
    import common from '@ohos.app.ability.common';
    import router from '@ohos.router';
    
    let context: common.UIAbilityContext = ...; // 获取UIAbility上下文
    let objParam = { id: 1, name: 'test' };
    
    let want = {
      bundleName: 'com.example.targetbundle',
      abilityName: 'TargetAbility',
      parameters: {
        // 序列化对象后传递
        data: JSON.stringify(objParam)
      }
    };
    context.startAbility(want).then(() => {
      console.info('跳转成功');
    }).catch((err: BusinessError) => {
      console.error(`跳转失败: ${err.code}, ${err.message}`);
    });
    
  2. 参数接收方(目标页面):

    • 在目标UIAbility的onCreate或目标页面的aboutToAppear生命周期中,通过want获取参数。
    • 将字符串参数反序列化为对象。
    import UIAbility from '@ohos.app.ability.UIAbility';
    import window from '@ohos.window';
    
    export default class TargetAbility extends UIAbility {
      onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
        // 从want中取出参数
        let dataStr = want.parameters?.data as string;
        if (dataStr) {
          let objParam = JSON.parse(dataStr); // 反序列化
          // 使用objParam进行后续业务逻辑
        }
      }
    }
    

注意事项:

  • 序列化限制:只能传递可序列化的数据(如基本类型、数组、简单对象),函数、类实例等不可传递。
  • 数据大小want参数有大小限制(通常约1MB),过大数据需考虑其他方式(如分布式对象、文件共享)。
  • 页面级导航:若仅在同一UIAbility内进行页面跳转,可使用router.pushUrl,并通过params传递序列化后的字符串参数。
    router.pushUrl({
      url: 'pages/TargetPage',
      params: { data: JSON.stringify(objParam) }
    });
    
    在目标页面的aboutToAppear中通过router.getParams()获取。

总结: HarmonyOS Next中通过routerstartAbility跳转时,对象参数需显式序列化为字符串传递,并在接收端反序列化。跨UIAbility跳转使用want参数,页面内跳转使用routerparams参数。

回到顶部