router.pushUrl不再被推荐使用

新的导航系统Navigation,你是不是被各种官方示例、代码片段搞得头都大了。

有的示例建议你通过onReady或者aboutToApper来获取NavPathStack。

有的让你通过Param来获取,有的文档还很旧,还建议你去main_pages.json添加路由。

各种绕各种迷糊。

其实,用@Consume或@Consumer就行了。

第一步在第一个页面

@Entry
@ComponentV2
struct Splash {
  @Provider('pathStack') pathStack: NavPathStack = new NavPathStack();
  @Builder
  pathMap(routeName: string) {
    if (routeName === 'Main') {
      Main()
    } else if (routeName === 'page2') {
      page2()
    } //这里无限else if要纳入导航的页面。
  }
build() {
    Navigation(this.pathStack) {
        ...
    }
    .navDestination(this.pathMap)
  }
}

其他所有页面一行即可。

@Consumer('pathStack') pathStack: NavPathStack = new NavPathStack();

在任何地方调用

this.pathStack.pushPath({ name: 'pageName' });

以上就是那么简单清晰。

细节一:你的子页面必须export,不能有@Entry装饰符,build内第一个标签必须是NavDestination

@ComponentV2
export struct RecordList {
build() {
    NavDestination() {}
}
}

细节二:退回指定页面可以使用

this.pathStack.popToName('Main');

细节三:导航页面A->B->A-.B,这时后退就会退两次A和B页面,如果不想这样,可以用launchMode:

this.pathStack.pushPath(
            { name: 'Page5' },
            { launchMode: LaunchMode.POP_TO_SINGLETON }
          )

细节四:从一个页面(比如Page1)返回时,想要触发事件,除了用emitter.emit(),其实在pathStack可以这样回调

 this.pathStack.pushPath({ name: 'Page2',onPop:(evt:PopInfo)=>{
        let data = evt.result;
        console.log(data);    //'hetui!'
    } 
})

在Page2页面调用pop来返回时,带上你要返回的参数,比如'hetui',则Page1的回调就会触发onPop

this.pathStack.pop('hetui!');

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐