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

运行效果图如下:

相关推荐
空潭冷月31 分钟前
HarmonyOS5:鸿蒙旅游类应用开发实践
harmonyos
空潭冷月36 分钟前
HarmonyOS5:鸿蒙体育类应用开发实践
harmonyos
全栈若城41 分钟前
71.[HarmonyOS NEXT 实战案例十] 电子书网格布局(上)
harmonyos
全栈若城42 分钟前
85.[HarmonyOS NEXT 实战案例十七] 设置选项列表网格布局(下)
harmonyos
全栈若城43 分钟前
73.[HarmonyOS NEXT 实战案例十一] 智能家居控制面板网格布局(上)
harmonyos
半路下车5 小时前
【Harmony OS 5】HarmonyOS应用测试指南
设计模式·harmonyos
移动端开发者5 小时前
鸿蒙Next自定义双滑块滑动条实现方案
harmonyos
SunFlower015 小时前
Harmony-websocket(一)
harmonyos
颜颜yan_5 小时前
深入解析HarmonyOS5 UIAbility组件:从核心架构到实战应用
架构·harmonyos·鸿蒙·鸿蒙系统
程序员小刘5 小时前
【HarmonyOS 5】教育开发实践详解以及详细代码案例
华为·wpf·harmonyos