前言
基于Router模块的页面路由主要有两种方式:
-
router.pushUrl()
:目标页压入页面栈,保留当前页状态,可通过返回键或router.back()
返回当前页,适用于通用跳转场景。 -
router.replaceUrl()
:目标页替换当前页并销毁当前页资源,适用于登录后跳转首页等需清除历史页的场景。
下面将展示如何通过router实现页面跳转
注:本文接上一讲内容,首先将目录结构进行一下调整,上一讲的multihap不再直接放在首页Index.ets中,首页将作为后续所讲各个基础开发知识点的入口。接着在首页中增加各个功能按钮,通过这些按钮跳转到multihap功能、页面路由跳转功能以及后续其他的各个基础功能开发功能中。
一、调整multihap目录结构
1、在pages目录下新建multihap目录
2、在multihap目录上新建页面文件MultiHap.ets
3、将Index.ets中的代码拷贝到MultiHap.ets中
import { common } from '@kit.AbilityKit';
import Logger from '../../util/Logger'
import { BusinessError } from '@kit.BasicServicesKit';
const TAG: string = 'MultiHap';
const AUDIO: string = 'audio';
const VIDEO: string = 'video';
const BUNDLE_NAME: string = 'com.example.helloworld';
const AUDIO_ABILITY_NAME: string = "AudioAbility";
const VIDEO_ABILITY_NAME: string = "VideoAbility";
@Entry
@Component
struct Multihap {
private context?: common.UIAbilityContext
build() {
Row() {
Column() {
Button(AUDIO)
.fontSize(50)
.fontWeight(FontWeight.Bold)
.onClick(() => {
if (this.context) {
this.context.startAbility({
bundleName: BUNDLE_NAME,
abilityName: AUDIO_ABILITY_NAME
}).then(() => {
Logger.info(TAG, 'start audio ability success')
}).catch((error: BusinessError) => {
Logger.error(TAG, 'start audio ability failed, error: ' + JSON.stringify(error))
})
}
})
.id('btnAudio')
.margin({ bottom: 20 })
Button(VIDEO)
.fontSize(50)
.fontWeight(FontWeight.Bold)
.onClick(() => {
if (this.context) {
this.context.startAbility({
bundleName: BUNDLE_NAME,
abilityName: VIDEO_ABILITY_NAME
}).then(() => {
Logger.info(TAG, 'start video ability success')
}).catch((error: BusinessError) => {
Logger.error(TAG, 'start video ability failed, error: ' + JSON.stringify(error))
})
}
})
.id('btnVideo')
}
.width('100%')
}
.height('100%')
}
aboutToAppear() {
this.context = getContext(this) as common.UIAbilityContext
}
}
4、修改Index.ets代码,使用如下代码覆盖原代码
import router from '@ohos.router';
const MULTIHAP: string = 'MultiHap';
@Entry
@Component
struct Index {
build() {
Row() {
Column() {
Button(MULTIHAP)
.onClick(() => {
router.pushUrl({
url: 'pages/multihap/MultiHap'
});
})
}
}
}
}
5、编译并运行,在模拟器上展示结果如下
点击MultiHap按钮跳转到MultiHap页面
二、页面路由跳转功能实现
1、参考上面的方法在pages目录下创建pagerouter目录
2、在pagerouter目录下创建4个页面文件:
其中:PageRouting.ets 页面跳转功能主入口
PushUrlPage.ets 使用PushUrl跳转到的页面文件
PushUrlSinglePage.ets 使用PushUrl并设置了单例模式跳转到的页面文件
ReplaceUrlPage.ets 使用使用ReplaceUrl跳转到的页面文件
3、分别在页面文件中拷贝如下代码
PageRouting.ets:
import router from '@ohos.router';
import { BusinessError } from '@kit.BasicServicesKit';
import RouterParam from '../../common/RouterParam';
import Logger from '../../util/Logger'
const PUSHURLPAGE: string = 'PushUrlPage';
const REPLACEURLPAGE: string = 'ReplaceUrlPage';
const PUSHURLSINGLEPAGE: string = 'PushUrlSinglePage';
const TAG: string = 'PageRouting';
@Entry
@Component
struct PageRouting {
@State message: string = 'Hello World';
onPageShow() {
Logger.info(TAG, "onPageShow");
}
build() {
//RelativeContainer() {
Row() {
Column() {
Button(PUSHURLPAGE)
.onClick(() => {
try {
router.pushUrl({ // 压入页面栈,可通过router.back()返回原页
url: 'pages/pagerouter/PushUrlPage',
params: new RouterParam('Open new page by pushUrl') // 传递到新页面的参数,如果不需要传递参数,这个字段可以不需要
});
} catch (err) {
let message = (err as BusinessError).message;
let code = (err as BusinessError).code;
console.error(`pushUrl failed, code is ${code}, message is ${message}`);
}
})
Button(REPLACEURLPAGE)
.onClick(() => {
router.replaceUrl({ // 销毁当前页,无法返回原页
url: 'pages/pagerouter/ReplaceUrlPage',
params: new RouterParam('Open new page by replaceUrl')
});
})
Button(PUSHURLSINGLEPAGE)
.onClick(() => {
router.pushUrl({ // 复用已有页面实例,减少内存消耗
url: 'pages/pagerouter/PushUrlSinglePage',
params: new RouterParam('Open new page by pushUrl, the mode is [single]\'')
},
router.RouterMode.Single,
(err: Error) => {
if (err) {
let message = (err as BusinessError).message;
let code = (err as BusinessError).code;
console.error(`pushUrl failed, code is ${code}, message is ${message}`);
return;
}
console.info('pushUrl success');
});
})
}
}
}
}
PushUrlPage.ets:
import { router } from '@kit.ArkUI';
import RouterParam from '../../common/RouterParam';
@Entry
@Component
struct PushPageUrl {
@State params: RouterParam = router.getParams() as RouterParam
@State message: string = this.params.info;
build() {
RelativeContainer() {
Text(this.message)
.id('PushPageUrlHelloWorld')
.fontSize($r('app.float.page_text_font_size'))
.fontWeight(FontWeight.Bold)
.alignRules({
center: { anchor: '__container__', align: VerticalAlign.Center },
middle: { anchor: '__container__', align: HorizontalAlign.Center }
})
.onClick(() => {
this.message = 'Welcome';
})
}
.height('100%')
.width('100%')
}
}
PushUrlSinglePage.ets
import { router } from '@kit.ArkUI';
import RouterParam from '../../common/RouterParam';
@Entry
@Component
struct PushUrlSinglePage {
@State params: RouterParam = router.getParams() as RouterParam
@State message: string = this.params.info;
build() {
RelativeContainer() {
Text(this.message)
.id('PushUrlSinglePageHelloWorld')
.fontSize($r('app.float.page_text_font_size'))
.fontWeight(FontWeight.Bold)
.alignRules({
center: { anchor: '__container__', align: VerticalAlign.Center },
middle: { anchor: '__container__', align: HorizontalAlign.Center }
})
.onClick(() => {
this.message = 'Welcome';
})
}
.height('100%')
.width('100%')
}
}
ReplaceUrlPage.ets:
import { router } from '@kit.ArkUI';
import RouterParam from '../../common/RouterParam';
@Entry
@Component
struct ReplaceUrlPage {
@State params: RouterParam = router.getParams() as RouterParam
@State message: string = this.params.info;
build() {
RelativeContainer() {
Text(this.message)
.id('ReplaceUrlPageHelloWorld')
.fontSize($r('app.float.page_text_font_size'))
.fontWeight(FontWeight.Bold)
.alignRules({
center: { anchor: '__container__', align: VerticalAlign.Center },
middle: { anchor: '__container__', align: HorizontalAlign.Center }
})
.onClick(() => {
this.message = 'Welcome';
})
}
.height('100%')
.width('100%')
}
}
4、在Index.ets中增加入口按钮代码
Button(PAGEROUTING)
.onClick(() => {
router.pushUrl({
url: 'pages/pagerouter/PageRouting'
});
})
5、编译并运行,在模拟器上展示结果如下
点击PageRouting按钮跳转到PageRouting主页面
点击相应的按钮将展示相应的页面,然后点模拟器上的返回键将返回上一页,其中将看到ReplaceUrlPage直接跳转到了Index首页,这是因为使用ReplaceUrl方法是将PageRouting主页面置换成了ReplaceUrlPage页面,PageRouting在页面栈中已经没有了,所以会直接返回Index首页。
完整的源码工程见附件:一步一步教你进行鸿蒙应用开发代码工程.zip
至此就完成了几种基本的页面路由功能,关键代码增加了相应的注释便于理解,如果还有疑问请在评论区留言,下一章节将展示页面布局相关的开发,请大家关注后续更新。