在创建项目时:
在src/main/ets/entryability目录下,会生成EntryAbility.ts
在src/main/ets/pages目录下,会生成一个Index页面。
在EntryAbility的onWindowStageCreate方法中指定了应用的入口页面
那么,入口页面如何跳转到其他页面呢?
HarmonyOS提供了Router模块,通过不同的url地址,可以方便地进行页面路由,轻松地访问不同的页面。
导入@ohos.router (页面路由)
import { router } from '@kit.ArkUI';
AI 代码解读
常见用法
API 说明
router.pushUrl(options: RouterOptions) //跳转到指定页面 router.replaceUrl(options: RouterOptions) //替换当前页面 router.back(options?: RouterOptions) //返回上一页面或指定的页面 router.clear() //清空所有历史页面,仅保留当前页面记录。
AI 代码解读
实例演示
首页→登录→个人中心
home
import {router} from '@kit.ArkUI' @Entry @Component struct Index { @State message: string = '首页'; @State isLogin:boolean=true; build() { RelativeContainer() { Button("个人中心").onClick(()=>{ if(this.isLogin){ router.pushUrl({url:'pages/Person'}) }else{ router.pushUrl({url:'pages/Login'}) } }) Text(this.message) .id('HelloWorld') .fontSize(50) .fontWeight(FontWeight.Bold) .alignRules({ center: { anchor: '__container__', align: VerticalAlign.Center }, middle: { anchor: '__container__', align: HorizontalAlign.Center } }) } .height('100%') .width('100%') } }
AI 代码解读
login
import { router } from '@kit.ArkUI'; @Entry @Component struct Login { @State message: string = '登录/注册'; build() { Column({space:10}) { Row(){ Button("返回").onClick(()=>{ router.back() }).backgroundColor("#CCCCCC") }.width("100%") Text(this.message) .id('LoginHelloWorld') .fontSize(50) .fontWeight(FontWeight.Bold) TextInput({placeholder:"请输入用户名/手机号"}) TextInput({placeholder:"请输入密码"}).type(InputType.Password) Button("提交").onClick(()=>{ // router.pushUrl({url:"pages/Person"});// 首页 - 登录页 - 个人中心页 - 返回:首页 router.replaceUrl({url:"pages/Person"});// 首页 -(登录页:替换成个人中心页)-返回:首页 }) } .height('100%') .width('100%') } }
AI 代码解读
person
import { router } from '@kit.ArkUI'; @Entry @Component struct Person { @State message: string = '个人中心'; build() { Column() { Button("返回").onClick(()=>{ router.back() }).backgroundColor("#CCCCCC") Text(this.message) .id('PersonHelloWorld') .fontSize(50) .fontWeight(FontWeight.Bold) Button("清空页面历史记录").onClick(()=>{ router.clear() }) } .height('100%') .width('100%') } }
AI 代码解读