例如从A页面跳转到B页面并传递参数?
在ArkUI中实现页面跳转及传参主要通过router
模块实现,以下是具体实现方式:
配置路由(在module.json5
中声明页面路由)
"pages": [
"pages/PageA",
"pages/PageB"
]
页面A跳转逻辑(传递参数)
// PageA.ets
import router from '@ohos.router';
@Entry
@Component
struct PageA {
build() {
Column() {
Button('跳转到PageB')
.onClick(() => {
// 携带参数跳转
router.pushUrl({
url: 'pages/PageB',
params: {
name: 'ArkUI',
id: 123
}
})
})
}
}
}
页面B接收参数
// PageB.ets
import router from '@ohos.router';
@Entry
@Component
struct PageB {
private receivedParams: object = router.getParams() || {};
aboutToAppear() {
// 获取传递的参数
console.log('收到参数:', this.receivedParams);
}
build() {
Column() {
Text(`名称:${this.receivedParams['name']}`)
Text(`ID:${this.receivedParams['id']}`)
}
}
}
关键点说明:
router.pushUrl()
:实现页面跳转的核心APIparams
对象:用于携带任意可序列化的参数router.getParams()
:在目标页面获取传递的参数aboutToAppear
生命周期获取参数,确保组件已初始化扩展特性:
路由模式:
router.pushUrl({
url: 'pages/PageB',
params: { /*...*/ }
}, router.RouterMode.Standard) // 标准模式(默认)
// 或 router.RouterMode.Single 单例模式
带回调的返回:
// 从PageB返回时携带数据
router.back({
url: 'pages/PageA',
params: { returnData: '来自B的数据' }
})
// PageA中监听返回参数
onPageShow() {
const params = router.getParams();
if (params) {
console.log('收到返回数据:', params['returnData']);
}
}
JSON.stringify()
序列化使用TypeScript接口规范参数类型
interface PageParams {
id: number;
name: string;
}
5 回答4.8k 阅读✓ 已解决
2 回答1k 阅读✓ 已解决
2 回答3.1k 阅读
1 回答2k 阅读
1 回答367 阅读
Router
组件进行页面导航,通过Router.pushUrl()
方法跳转到目标页面。pushUrl()
方法的params
参数中,以 Key-Value 形式传递参数。onPageShow()
生命周期方法中,通过this.routeParams
获取传递的参数。