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)
}
}

效果图:页面跳转流畅,控制台无报错,正确显示传递的数据。
更多关于HarmonyOS鸿蒙Next中兼容api12以上router模块化调用与参数传递的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS Next(API 12及以上)中,使用router进行模块化页面跳转并传递对象参数,需通过UIAbility路由与want参数实现。以下是关键步骤:
-
配置路由:在
module.json5中声明目标UIAbility的路由信息,确保srcEntry路径正确。 -
传递对象参数:
- 使用
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}`); });
- 使用
-
接收参数:在目标UIAbility的
onCreate或onNewWant生命周期中,通过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}`); } }
- 示例:
-
页面级跳转:若仅在同一个UIAbility内跳转页面,可使用
router.pushUrl,但传递复杂对象时仍需序列化,通过params传递。- 示例:
router.pushUrl({ url: 'pages/TargetPage', params: { userData: JSON.stringify({ name: '李四', age: 25 }) } });
- 示例:
注意事项:
- 确保传递的数据可序列化,避免包含不可序列化的对象(如函数、循环引用)。
- 跨设备传递时,需检查
deviceId和网络权限。 - 参数大小受系统限制,建议传递关键数据,大量数据使用数据库或文件共享。
这种方式兼容API 12及以上版本,符合HarmonyOS Next的模块化设计规范。


