在HarmonyOS开发中,如果你的项目当前使用的是router进行页面导航,并希望迁移到推荐使用的navgation模式,那么你需要了解两者之间的主要区别。
HarmonyOS推荐使用navgation机制来处理页面间的导航,因为它提供了更强大和灵活的方式来管理应用内部的页面跳转和状态管理。
步骤
1、更新依赖
确保项目依赖已经更新到最新版本。以包含最新的navgation功能支持。可能涉及到更新SDK版本或添加特定的库依赖。
2、修改配置文件
在config.json中,确认所有Abilities都正确配置了必要的信息,包括启动模式(launchType)等。
如果之前有自定义的路由配置,现在需要转换为navgation所需要的形式。
3、替换路由跳转逻辑
将原有的router.push()或类似的跳转方法替换为navgation提供的方法。
router实现方式
在发起跳转的页面(例如 FirstPage.ets
)中:
在目标页面(例如 SecondPage.ets
)中接收参数:
navigation
实现方式
在发起跳转的页面(例如 FirstPage.ets
)中:
在目标页面(例如 SecondPage.ets
)中接收参数:
navigation
实现方式(router
不支持直接获取返回结果)
在发起跳转的页面(例如 FirstPage.ets
)中:
import { NavigationService } from '@ohos.navigation';
@Entry
@Component
struct FirstPage {private navigationService = NavigationService.getInstance();private resultMessage: string = '';async handleNavigate() {try {const result = await this.navigationService.pushForResult({name: 'pages/SecondPage',params: {message: 'Hello from FirstPage!'}});this.resultMessage = result;} catch (error) {console.error('Navigation error: ' + error);}}build() {Column({ space: 50 }) {Button('Navigate to SecondPage and get result').onClick(() => {this.handleNavigate();})Text(`Received result: ${this.resultMessage}`)}.width('100%')}
}
在目标页面(例如 SecondPage.ets
)中设置返回结果
import { NavigationService } from '@ohos.navigation';@Entry
@Component
struct SecondPage {private navigationService = NavigationService.getInstance();build() {Column({ space: 50 }) {Button('Go back and send result').onClick(() => {this.navigationService.setResult('Result from SecondPage');this.navigationService.pop();})}.width('100%')}
}
不完善,待更新