HarmonyOS鸿蒙Next中兼容api12以上router模块化调用与参数传递

HarmonyOS鸿蒙Next中兼容api12以上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中兼容api12以上router模块化调用与参数传递的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


HarmonyOS Next的API 12及以上版本中,router模块支持模块化调用与参数传递。通过router模块的pushUrl方法,可在不同Ability或Page间导航,并使用params传递参数。接收方通过router.getParams()获取参数。模块化调用允许将功能封装为独立模块,通过router进行跨模块调用,提升代码复用性和可维护性。

在HarmonyOS Next(API 12及以上)中,使用router进行模块化页面跳转并传递对象参数,需通过UIAbility路由与want参数实现。以下是关键步骤:

  1. 配置路由:在module.json5中声明目标UIAbility的路由信息,确保srcEntry路径正确。

  2. 传递对象参数

    • 使用want参数携带数据,将对象序列化为字符串(如JSON)或转换为Parcelable类型。
    • 示例代码:
      import { BusinessError } from '@ohos.base';
      import common from '@ohos.app.ability.common';
      import router from '@ohos.router';
      
      let context = getContext(this) as common.UIAbilityContext;
      let want = {
        deviceId: '', // 留空表示本设备
        bundleName: 'com.example.app',
        abilityName: 'TargetAbility',
        parameters: {
          // 传递对象:序列化为JSON字符串
          userData: JSON.stringify({ name: '张三', age: 30 })
        }
      };
      context.startAbility(want).then(() => {
        console.info('跳转成功');
      }).catch((err: BusinessError) => {
        console.error(`跳转失败: ${err.code}, ${err.message}`);
      });
      
  3. 接收参数:在目标UIAbility的onCreateonNewWant生命周期中,通过want.parameters获取数据,并反序列化为对象。

    • 示例:
      import { UIAbility } from '@ohos.app.ability.UIAbility';
      
      export default class TargetAbility extends UIAbility {
        onCreate(want, launchParam) {
          let userData = JSON.parse(want.parameters?.userData as string);
          console.info(`收到参数: ${userData.name}, ${userData.age}`);
        }
      }
      
  4. 页面级跳转:若仅在同一个UIAbility内跳转页面,可使用router.pushUrl,但传递复杂对象时仍需序列化,通过params传递。

    • 示例:
      router.pushUrl({
        url: 'pages/TargetPage',
        params: { userData: JSON.stringify({ name: '李四', age: 25 }) }
      });
      

注意事项

  • 确保传递的数据可序列化,避免包含不可序列化的对象(如函数、循环引用)。
  • 跨设备传递时,需检查deviceId和网络权限。
  • 参数大小受系统限制,建议传递关键数据,大量数据使用数据库或文件共享。

这种方式兼容API 12及以上版本,符合HarmonyOS Next的模块化设计规范。

回到顶部