需求描述
Stage模型下的Ability开发,实现Ability内页面间的跳转和数据传递
注:本文的 API 基于 Stage模型 和 HarmonyOS 3.1 Developer Preview
页面效果
Ability概述
Ability框架概述-Ability开发-开发-HarmonyOS应用开发
Ability内页面跳转和数据传递
Ability的数据传递包括有Ability内页面的跳转和数据传递、Ability间的数据跳转和数据传递
页面路由,需要导入router模块,如下代码所示。
import router from '@ohos.router';
页面路由使用方法请参考官方文档
- router.clear() 方法清除页面栈中的所有历史页面,仅保留当前页面作为栈顶页面。
- API9及以上,router.push() 方法新增了mode参数,可以将mode参数配置为 router.RouterMode.Single 单实例模式和 router.RouterMode.Standard 标准模式。
在单实例模式下:如果目标页面的url在页面栈中已经存在同url页面,离栈顶最近的同url页面会被移动到栈顶,移动后的页面为新建页,原来的页面仍然存在栈中,页面栈数量不变;如果目标页面的url在页面栈中不存在同url页面,按标准模式跳转,页面栈数量会加1。
代码实例
Index.ets
import router from '@ohos.router';
@Entry
@Component
struct Index {
@State message: string = '第一页'
@State dataFromIndex: string = ''
@State dataFromSecond: string = ''
onPageShow() {
this.dataFromSecond = router.getParams()?.['dataFromSecond']
}
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
Text('传递给第二页的数据:')
.margin({ top: 16 })
.fontSize(20)
.fontWeight(FontWeight.Bold)
TextInput()
.width('95%')
.onChange((value) => {
this.dataFromIndex = value
})
Text('从第二页返回的数据:')
.margin({ top: 16 })
.fontSize(20)
.fontWeight(FontWeight.Bold)
Text(this.dataFromSecond)
.fontSize(20)
.fontColor(Color.Green)
Button('下一页')
.width('50%')
.margin({ top: 16 })
.onClick(() => {
router.push({
url: 'pages/Second',
params: {
dataFromIndex: this.dataFromIndex
}
})
})
}
.width('100%')
}
.height('100%')
}
}
Second.ets
import router from '@ohos.router';
@Entry
@Component
struct Second {
@State message: string = '第二页'
@State dataFromIndex: string = router.getParams()?.['dataFromIndex']
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
Text(this.dataFromIndex)
.fontSize(20)
.margin({ top: 16 })
.fontColor(Color.Orange)
Button('清除页面栈')
.width('50%')
.margin({ top: 16 })
.onClick(() => {
router.clear()
})
Button('跳转第一页\n单实例模式')
.width('50%')
.margin({ top: 16 })
.onClick(() => {
router.push({
url: 'pages/Index',
params: {
dataFromSecond: '单例模式跳转的数据'
}
}, router.RouterMode.Single)
})
Button('返回')
.width('50%')
.margin({ top: 16 })
.onClick(() => {
router.back({
url: 'pages/Index',
params: {
dataFromSecond: '直接返回的数据'
}
})
})
}
.width('100%')
}
.height('100%')
}
}