介紹
本篇主要介紹如何在HarmonyOS中,在頁面跳轉(zhuǎn)之間如何傳值
HarmonyOS 的頁面指的是帶有@Entry裝飾器的文件,其不能獨(dú)自存在,必須依賴UIAbility這樣的組件容器
如下是官方關(guān)于State模型開發(fā)模式下的應(yīng)用包結(jié)構(gòu)示意圖,Page就是帶有@Entry裝飾器的文件
那么在頁面跳轉(zhuǎn)時(shí),在代碼層面最長路徑其實(shí)是有兩步 1,打開UIAbility 2. 打開Page
整體交互效果
傳值理論
準(zhǔn)備
我們熟讀玩文檔后,開始創(chuàng)建一個(gè)Demo工程,選擇Stage模型
代碼實(shí)踐
1.定制主入口頁面
功能
- 頁面曝光停留時(shí)長計(jì)算
- 增加進(jìn)入二級頁面入口
import systemDateTime from '@ohos.systemDateTime'
import router from '@ohos.router'
@Entry
@Component
struct Index {
@State message: string = '頁面跳轉(zhuǎn)'
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" //三級頁面
]
}
功能
- 展示主入口頁面停留時(shí)間
- 添加通過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為空表示本設(shè)備
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. 添加三級頁面
注意
先要添加注冊一個(gè)新的容器,這里命名為: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 三種傳值方式的數(shù)據(jù)
LocalStorageAbilityPage.ets 文件
- 展示LocalStorage,EventHub方式的數(shù)據(jù)
import router from '@ohos.router'; import common from '@ohos.app.ability.common'; // 通過GetShared接口獲取stage共享的LocalStorage實(shí)例 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傳值內(nèi)容') 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傳值內(nèi)容') 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') }); } }
審核編輯 黃宇
-
鴻蒙
+關(guān)注
關(guān)注
57文章
2302瀏覽量
42689 -
HarmonyOS
+關(guān)注
關(guān)注
79文章
1966瀏覽量
29962 -
鴻蒙OS
+關(guān)注
關(guān)注
0文章
188瀏覽量
4359
發(fā)布評論請先 登錄
相關(guān)推薦
評論