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

运行效果图如下:

相关推荐
敢嗣先锋2 小时前
鸿蒙5.0实战案例:基于ArkUI启动冷启动过程最大连续丢帧数问题分析思路&案例
性能优化·移动开发·多线程·harmonyos·arkui·鸿蒙开发
HarmonyOS_SDK2 小时前
智能网络感知,打造极致流畅的鸿蒙原生版中国移动云盘图文体验
harmonyos
SuperHeroWu72 小时前
【HarmonyOS Next】鸿蒙应用进程和线程详解
华为·线程·进程·harmonyos·鸿蒙
MardaWang3 小时前
HarmonyOS开发,遇到 Object.assign(this, source)报错怎么解决?
typescript·harmonyos
敲代码的鱼哇5 小时前
设备唯一ID获取,支持安卓/iOS/鸿蒙Next(uni-device-id)UTS插件
android·ios·uniapp·harmonyos
别说我什么都不会5 小时前
鸿蒙轻内核M核源码分析系列十 软件定时器Swtmr
操作系统·harmonyos
8931519606 小时前
《鸿蒙开发-答案之书》获取视频第一帧和视频时间
harmonyos·鸿蒙系统·鸿蒙开发·鸿蒙教程·鸿蒙视频第一帧·鸿蒙获取视频时长
林钟雪6 小时前
HarmonyOS全栈开发指南:从入门到精通,构建万物智联的未来生态(二)
华为·harmonyos
程序边界7 小时前
深度探索:DeepSeek与鸿蒙HarmonyOS应用开发的深度融合
华为·harmonyos
SameX8 小时前
HarmonyOS Next人脸活体检测技术深度剖析
harmonyos