HarmonyOS router页面跳转

默认启动页面index.ets

复制代码
import  router from '@ohos.router'
import  {BusinessError} from '@ohos.base'

@Entry
@Component
struct Index {
  @State message: string = 'Hello World';

  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)

        //添加按钮,以响应用户点击
        Button(){
          Text('Next')
            .fontSize(30)
            .fontWeight(FontWeight.Bold)
        }
        .type(ButtonType.Capsule)
        .margin({
          top:20
        })
        .backgroundColor('#00D9FFB')
        .width('40%')
        .height('5%')
        //跳转按钮绑定onclick事件,点击跳转到目标页面
        .onClick(()=>{
          console.log(`Succeeded in clicking the 'Next' button.`);
          router.pushUrl({url:'pages/TargetPage'}).then(()=>{
            console.info('Succeeded in jumping to the second page.')
          }).catch((err: BusinessError) => {
            console.error(`Failed to jump to the second page.Code is ${err.code}, message is ${err.message}`)
          })
        })
      }
      .width('100%')
    }
    .height('100%')
  }
}

跳转目标页面TargetPage.ets

复制代码
// 导入页面路由模块
import router from '@ohos.router';
import { BusinessError } from '@ohos.base';

@Entry
@Component
struct TargetPage {
  @State message: string = '鸿蒙小趣';

  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
        Button(){
          Text('Back')
            .fontSize(25)
            .fontWeight(FontWeight.Bold)
        }
        .type(ButtonType.Capsule)
        .margin({top:20})
        .backgroundColor('#0D9FFB')
        .width('40%')
        .height('5%')
        // 返回按钮绑定onClick事件,点击按钮时返回到第一页
        .onClick(()=>{
          console.info(`Succeeded in clicking the 'Back' button.`)
          try {
            // 返回第一页
            router.back()
            console.info('Succeeded in returning to the first page.')
          }catch (err){
            let code = (err as BusinessError).code;
            let message = (err as BusinessError).message;
            console.error(`Failed to return to the first page.Code is ${code}, message is ${message}`)
          }
        })
      }
      .width('100%')
    }
    .height('100%')
  }
}

运行效果图如下:

相关推荐
三声三视9 小时前
Electron 本地图片在鸿蒙 PC 上白图,我注册了个自定义协议
electron·harmonyos·鸿蒙
李二。9 小时前
日历日程管理工具 — 基于 HarmonyOS NEXT (API 23+) 的 ArkTS 纯声明式实现
华为·harmonyos
金启攻9 小时前
鸿蒙原生应用实战(三):搜索与详情页 —— 多维度筛选与动态路由
华为·harmonyos
祭曦念10 小时前
鸿蒙原生Gauge仪表盘组件深度实践
华为·harmonyos
风华圆舞10 小时前
DevEco Studio 和 Flutter 工具链如何协同工作
flutter·华为·架构·harmonyos
祭曦念10 小时前
鸿蒙Next实战:从零构建每日打卡应用
华为·harmonyos
yuegu77710 小时前
HarmonyOS应用<节气通>开发第20篇:ArticleCard组件封装
华为·harmonyos
金启攻10 小时前
鸿蒙原生应用实战(二):首页开发 —— 周历导航与@Builder组件化实践
华为·harmonyos
hahjee11 小时前
【鸿蒙PC】kcp 移植:AtomCode Skills 4 步速通单文件 C 库适配
c语言·华为·harmonyos
风满城3311 小时前
鸿蒙原生应用实战(四):歌单管理 —— 创建歌单与歌曲编排
华为·harmonyos