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

运行效果图如下:

相关推荐
Georgewu9 天前
【HarmonyOS 5】鸿蒙跨平台开发方案详解(一)
flutter·harmonyos
万少9 天前
重磅推出 🔥 HarmonyOS AI 助手 CodeGenie V6 的使用教程
前端·harmonyos
我睡醒再说9 天前
纯血HarmonyOS5 打造小游戏实践:绘画板(附源文件)
harmonyos
我睡醒再说9 天前
HarmonyOS 5 ArkTS Worker线程:构建高性能移动应用的并行计算引擎
harmonyos
我睡醒再说9 天前
纯血HarmonyOS5 打造小游戏实践:扫雷(附源文件)
harmonyos
二流小码农9 天前
鸿蒙开发:基于node脚本实现组件化运行
android·ios·harmonyos
Moximxxx9 天前
Harmory Next 下拉刷新 悬浮loading效果
harmonyos
中雨202510 天前
HarmonyOS Next快速入门:类型定义和国际化
harmonyos
ChinaDragon10 天前
HarmonyOS:使用命令行CMake构建NDK工程
harmonyos
ChinaDragon10 天前
HarmonyOS:使用DevEco Studio模板构建NDK工程
harmonyos