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

运行效果图如下:

相关推荐
默 语16 小时前
Electron 应用中的系统检测方案对比与鸿蒙适配实践
javascript·electron·harmonyos·gwo
ifeng091818 小时前
HarmonyOS资源加载进阶:惰性加载、预加载与缓存机制
深度学习·缓存·harmonyos
爱笑的眼睛1121 小时前
HarmonyOS列表项滑动操作深度解析:从基础实现到高级交互
华为·harmonyos
ifeng09181 天前
HarmonyOS状态管理精细化:控制渲染范围与变量拆分策略
华为·harmonyos
万少1 天前
记第一次鸿蒙应用上架之旅:一场略带遗憾的旅途
前端·harmonyos
HarmonyOS_SDK2 天前
【FAQ】HarmonyOS SDK 闭源开放能力 — Network Kit
harmonyos
爱笑的眼睛112 天前
HarmonyOS中MenuItem事件处理的深度解析:从基础到分布式实践
华为·harmonyos
东林知识库2 天前
鸿蒙5:HarmonyOS应用开发-项目打包申请证书和上架
华为·harmonyos
HMS Core2 天前
【FAQ】HarmonyOS SDK 闭源开放能力 — Push Kit
linux·python·华为·harmonyos
二流小码农2 天前
鸿蒙开发:this的指向问题
android·ios·harmonyos