export class RouterParams { text: string; constructor(str: string) { this.text = str; } } @Entry @Component struct NavigationRouterDemo { pageInfos: NavPathStack = new NavPathStack(); build() { Navigation(this.pageInfos) { Column({ space: 20 }) { Button('Navigation跳转', { stateEffect: true, type: ButtonType.Capsule }) .width('80%') .height(40) .onClick(() => { // navigation路由跳转 const info = new RouterParams('以Navigation方式进行跳转'); this.pageInfos.pushPathByName('PageD', info); }); Button('Router跳转', { stateEffect: true, type: ButtonType.Capsule }) .width('80%') .height(40) .onClick(() => { // router路由跳转 this.getUIContext() .getRouter() .pushUrl({ url: 'pages/PageD', params: new RouterParams('以Router方式进行跳转') }); }); } .width('100%') .height('100%') .justifyContent(FlexAlign.Center) .padding('20vp'); } .title('Navigation-Router跳转时判断路由来源'); } }
pageD页面代码如下:
import { RouterParams } from './NavigationRouterDemo'; @Builder export function PageDBuilder() { PageD(); } @Entry @Component struct PageD { pageInfos: NavPathStack = new NavPathStack(); @State message: string = 'test'; build() { NavDestination() { Column({ space: 20 }) { Text(this.message); } .justifyContent(FlexAlign.Center) .height('100%') .width('100%'); } .title('PageD') .onReady((context: NavDestinationContext) => { this.pageInfos = context.pathStack; if (JSON.stringify(this.getUIContext().getRouter().getParams()) === undefined) { this.message = JSON.stringify(this.pageInfos.getParamByName('PageD')); console.info('navigation 跳转'); } else { this.message = (this.getUIContext().getRouter().getParams() as RouterParams).text; console.info('router 跳转'); } }); } }
路由表router_map.json如下:
{
"routerMap": [
{
"name": "PageD",
"pageSourceFile": "src/main/ets/pages/PageD.ets",
"buildFunction": "PageDBuilder",
"data": {
"description": "this is PageD"
}
}
]
}