鸿蒙HarmonyOS开发实战: 页面传值跳转
介绍
本篇主要介绍如何在HarmonyOS中,在页面跳转之间如何传值
HarmonyOS 的页面指的是带有@Entry装饰器的文件,其不能独自存在,必须依赖UIAbility这样的组件容器
如下是官方关于State模型开发模式下的应用包结构示意图,Page就是带有@Entry装饰器的文件
那么在页面跳转时,在代码层面最长路径其实是有两步 1,打开UIAbility 2. 打开Page
整体交互效果
传值理论
- 基于LocalStorage
- 基于EventHub
- 基于router
准备
请参照官方指导,创建一个Demo工程,选择Stage模型
代码实践
1.定制主入口页面
功能
- 页面曝光停留时长计算
- 增加进入二级页面入口
import systemDateTime from '@ohos.systemDateTime'
import router from '@ohos.router'
@Entry
@Component
struct Index {
@State message: string = '页面跳转'
private showDuration: number = 0
onPageShow() {
this.showDuration = 0
systemDateTime.getCurrentTime(false, (error, data) => {
if(!error){
this.showDuration = data
}
})
}
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
.onClick(()=>{
systemDateTime.getCurrentTime(false, (error, data) => {
router.pushUrl({ url: 'pages/OpenPage', params: {
"from": "pages/Home.ets",
"data": {
"duration":(data - this.showDuration)
}
} })
.then(() => {
console.info('Succeeded in jumping to the second page.')
}).catch((error) => {
console.log(error)
})
})
})
}
.width('100%')
}
.height('100%')
}
}
2.添加二级页面
注意
OpenPage.ets需要在main_pages.json中的注册
{
"src": [
"pages/Index" //主入口页面
,"pages/OpenPage" //二级页面
,"pages/Test" //三级页面
,"pages/LocalStorageAbilityPage" //三级页面
]
}
功能
- 展示主入口页面停留时间
- 添加通过UIAbility方式打开页面的入口
- 添加通过router.pushUrl方式打开页面的入口
/**
* 路由 3.1/4.0 文档
* https://developer.harmonyos.com/cn/docs/documentation/doc-references-V3/js-apis-router-0000001478061893-V3#ZH-CN_TOPIC_0000001523808578__routerpushurl9
*
*/
import router from '@ohos.router';
import common from '@ohos.app.ability.common';
@Entry
@Component
struct OpenPageIndex{
@State extParams: string = ''
private expParamsO: Object
private context = getContext(this) as common.UIAbilityContext;
aboutToAppear(){
this.expParamsO = router.getParams();
this.extParams = JSON.stringify(this.expParamsO, null, '\t');
}
build(){
Column(){
List(){
ListItemGroup() {
ListItem() {
Text(this.extParams)
.width('96%')
.fontSize(18)
.fontColor(Color.Green)
.backgroundColor(Color.White)
}.width('100%')
.align(Alignment.Start)
.backgroundColor(0xFFFFFF)
.borderRadius('16vp')
.padding('12vp')
}.divider({
strokeWidth: 1,
startMargin: 0,
endMargin: 0,
color: '#ffe5e5e5'
})
ListItemGroup() {
ListItem() {
Text('启动UIAbility页面')
.width('96%')
.fontSize(18)
.fontColor(Color.Black)
.backgroundColor(Color.White)
}.width('100%')
.height(50)
.align(Alignment.Start)
.backgroundColor(0xFFFFFF)
.padding({ left: 10 })
.onClick(() => {
this.startAbilityTest('LocalStorageAbility')
})
ListItem() {
Text('启动@Entry页面')
.width('96%')
.fontSize(18)
.fontColor(Color.Black)
.backgroundColor(Color.White)
}.width('100%')
.height(50)
.align(Alignment.Start)
.backgroundColor(0xFFFFFF)
.padding({ left: 10 })
.onClick(() => {
router.pushUrl({ url: 'pages/Test', params: {
"from": "pages/OpenPage.ets"
} })
.then(() => {
console.info('Succeeded in jumping to the second page.')
}).catch((error) => {
console.log(error)
})
})
}.divider({
strokeWidth: 1,
startMargin: 0,
endMargin: 0,
color: '#ffe5e5e5'
})
}.width('100%').height('90%')
.divider({
strokeWidth: px2vp(20),
startMargin: 0,
endMargin: 0,
color: '#ffe5e5e5'
})
}.width('100%').height('100%')
.padding({ top: px2vp(111) , left: '12vp', right: '12vp'})
.backgroundColor('#ffe5e5e5')
}
async startAbilityTest(name: string) {
try {
let want = {
deviceId: '', // deviceId为空表示本设备
bundleName: 'com.harvey.testharmony',
abilityName: name,
parameters:{
from: 'OpenPage.ets',
data: {
hello: 'word',
who: 'please'
}
}
};
let context = getContext(this) as common.UIAbilityContext;
await context.startAbility(want);
console.info(`explicit start ability succeed`);
} catch (error) {
console.info(`explicit start ability failed with ${error.code}`);
}
}
}
3. 添加三级页面
注意
先要添加注册一个新的容器,这里命名为:LocalStorageAbility.ets 容器需要在module.json5中声明
{
"name": "LocalStorageAbility",
"srcEntry": "./ets/entryability/LocalStorageAbility.ets",
"description": "$string:EntryAbility_desc",
"icon": "$media:icon",
"label": "$string:EntryAbility_label",
"startWindowIcon": "$media:icon",
"startWindowBackground": "$color:start_window_background"
}
import window from '@ohos.window';
import UIAbility from '@ohos.app.ability.UIAbility';
let para:Record<string,string> = { 'PropA': JSON.stringify({ 'from': 'LocalStorageAbility'}) };
let localStorage: LocalStorage = new LocalStorage(para);
export default class LocalStorageAbility extends UIAbility {
storage: LocalStorage = localStorage
onCreate(want, launchParam) {
}
onWindowStageCreate(windowStage: window.WindowStage) {
super.onWindowStageCreate(windowStage)
windowStage.loadContent('pages/LocalStorageAbilityPage', this.storage, (err, data) => {
if (err.code) {
return;
}
setTimeout(()=>{
let eventhub = this.context.eventHub;
console.log(para['PropA'])
eventhub.emit('parameters', para['PropA']);
}, 0)
});
}
}
Test.ets和LocalStorageAbilityPage.ets需要在main_pages.json中的注册
{
"src": [
"pages/Index" //主入口页面
,"pages/OpenPage" //二级页面
,"pages/Test" //三级页面
,"pages/LocalStorageAbilityPage" //三级页面
]
}
功能
- 展示基于LocalStorage,EventHub,router 三种传值方式的数据
LocalStorageAbilityPage.ets 文件
- 展示LocalStorage,EventHub方式的数据
import router from '@ohos.router'; import common from '@ohos.app.ability.common'; // 通过GetShared接口获取stage共享的LocalStorage实例 let storage = LocalStorage.GetShared() @Entry(storage) @Component struct LocalStorageAbilityPageIndex { @State message: string = '' // can access LocalStorage instance using // @LocalStorageLink/Prop decorated variables @LocalStorageLink('PropA') extLocalStorageParms: string = ''; context = getContext(this) as common.UIAbilityContext; aboutToAppear(){ this.eventHubFunc() } build() { Row() { Column({space: 50}) { Column({space: 10}){ Text('LocalStorage传值内容') Text(JSON.stringify(JSON.parse(this.extLocalStorageParms), null, '\t')) .fontSize(18) .fontColor(Color.Green) .backgroundColor(Color.White) .width('100%') .padding('12vp') .borderRadius('16vp') } Column({space: 10}){ Text('eventHub传值内容') Text(this.message) .fontSize(18) .fontColor(Color.Green) .backgroundColor(Color.White) .width('100%') .padding('12vp') .borderRadius('16vp') } }.width('100%').height('100%') .padding({ top: px2vp(111) , left: '12vp', right: '12vp'}) .backgroundColor('#ffe5e5e5') } .height('100%') } eventHubFunc() { this.context.eventHub.on('parameters', (...data) => { this.message = JSON.stringify(JSON.parse(data[0]), null, '\t') }); } }