鸿蒙OS开发实例:【页面传值跳转】

电子说

1.3w人已加入

描述

介绍

本篇主要介绍如何在HarmonyOS中,在页面跳转之间如何传值

HarmonyOS 的页面指的是带有@Entry装饰器的文件,其不能独自存在,必须依赖UIAbility这样的组件容器

如下是官方关于State模型开发模式下的应用包结构示意图,Page就是带有@Entry装饰器的文件

鸿蒙

那么在页面跳转时,在代码层面最长路径其实是有两步 1,打开UIAbility 2. 打开Page

整体交互效果

鸿蒙

传值理论

  1. 基于LocalStorage
  2. 基于EventHub
  3. 基于router

准备

鸿蒙

我们熟读玩文档后,开始创建一个Demo工程,选择Stage模型

代码实践

1.定制主入口页面

功能

  1. 页面曝光停留时长计算
  2. 增加进入二级页面入口
importsystemDateTimefrom'@ohos.systemDateTime'importrouterfrom'@ohos.router'@Entry@Componentstruct Index {@Statemessage:string='页面跳转'privateshowDuration:number=0onPageShow(){this.showDuration =0systemDateTime.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"//三级页面] }

功能

  1. 展示主入口页面停留时间
  2. 添加通过UIAbility方式打开页面的入口
  3. 添加通过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 * */importrouterfrom'@ohos.router';importcommonfrom'@ohos.app.ability.common';@Entry@Componentstruct OpenPageIndex{@StateextParams:string=''privateexpParamsO:Objectprivatecontext = getContext(this)ascommon.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') }asyncstartAbilityTest(name:string){try{letwant = {deviceId:'',// deviceId为空表示本设备bundleName:'com.harvey.testharmony',abilityName: name,parameters:{from:'OpenPage.ets',data: {hello:'word',who:'please'} } };letcontext = getContext(this)ascommon.UIAbilityContext;awaitcontext.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"}
importwindowfrom'@ohos.window';importUIAbilityfrom'@ohos.app.ability.UIAbility';letpara:Record<string,string> = {'PropA':JSON.stringify({'from':'LocalStorageAbility'}) };letlocalStorage: LocalStorage =newLocalStorage(para);exportdefaultclassLocalStorageAbilityextendsUIAbility{storage: LocalStorage =localStorageonCreate(want, launchParam){ }onWindowStageCreate(windowStage:window.WindowStage){super.onWindowStageCreate(windowStage) windowStage.loadContent('pages/LocalStorageAbilityPage',this.storage, (err, data) = > {if(err.code) {return; }setTimeout(()= >{leteventhub =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"//三级页面] }

功能

  1. 展示基于LocalStorage,EventHub,router 三种传值方式的数据
    LocalStorageAbilityPage.ets 文件
  • 展示LocalStorage,EventHub方式的数据
    importrouterfrom'@ohos.router';importcommonfrom'@ohos.app.ability.common';// 通过GetShared接口获取stage共享的LocalStorage实例letstorage = LocalStorage.GetShared()@Entry(storage)@Componentstruct LocalStorageAbilityPageIndex {@Statemessage:string=''// can access LocalStorage instance using// @LocalStorageLink/Prop decorated variables@LocalStorageLink('PropA') extLocalStorageParms:string=''; context = getContext(this)ascommon.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') }); } }

审核编辑 黄宇

打开APP阅读更多精彩内容
声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表德赢Vwin官网 网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉

全部0条评论

快来发表一下你的评论吧 !

×
20
完善资料,
赚取积分