程序员的知识教程库

网站首页 > 教程分享 正文

HarmonyOS NEXT - 页面路由(路由器web界面)

henian88 2025-04-08 14:23:14 教程分享 28 ℃ 0 评论

在创建项目时:

在src/main/ets/entryability目录下,会生成EntryAbility.ts

在src/main/ets/pages目录下,会生成一个Index页面。

在EntryAbility的onWindowStageCreate方法中指定了应用的入口页面

那么,入口页面如何跳转到其他页面呢?

HarmonyOS提供了Router模块,通过不同的url地址,可以方便地进行页面路由,轻松地访问不同的页面。

导入@ohos.router (页面路由)

```arkts

import { router } from '@kit.ArkUI';

```

常见用法

API 说明

```arkts

router.pushUrl(options: RouterOptions) //跳转到指定页面

router.replaceUrl(options: RouterOptions) //替换当前页面

router.back(options?: RouterOptions) //返回上一页面或指定的页面

router.clear() //清空所有历史页面,仅保留当前页面记录。

```

实例演示

首页→登录→个人中心

home

```arkts

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%')

}

}

```

login

```arkts

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%')

}

}

```

person

```arkts

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%')

}

}

```

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表