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

运行效果图如下:

相关推荐
脑极体1 小时前
点亮星河AI+鸿蒙,一座艺术场馆的日神觉醒
人工智能·华为·harmonyos
●VON1 小时前
鸿蒙Flutter实战:分类管理页BottomSheet CRUD
数据库·flutter·华为·harmonyos·鸿蒙
GitCode官方4 小时前
开源鸿蒙 PC 直播回顾|从环境搭建到真机验证:鸿蒙 PC 命令行迁移全链路。
华为·开源·harmonyos
想你依然心痛5 小时前
HarmonyOS 6(API 23)智能体驱动的沉浸式AR文化遗产数字修复工坊
华为·ar·harmonyos·智能体
largecode8 小时前
座机号码认证如何操作?申请热线实名名片,树立统一官方客服形象
linux·sql·华为·c#·.net·wpf·harmonyos
大雷神8 小时前
第07篇|权限分层策略:相机、定位、生物认证、手势为什么分开申请
harmonyos
●VON9 小时前
鸿蒙Flutter实战:水平滑动分类标签筛选栏
flutter·华为·harmonyos
小成Coder11 小时前
【Jack实战】如何用 Share Kit 接入碰一碰和 AI 隔空传送
华为·harmonyos·鸿蒙
●VON11 小时前
鸿蒙Flutter实战:24小时新建标签提示组件
android·flutter·华为·harmonyos·鸿蒙