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

运行效果图如下:

相关推荐
ShallowLin2 小时前
【HarmonyOS闯关习题】——DevEco Studio的使用
华为·harmonyos
科技与数码3 小时前
鸿蒙6.1小艺伴随式AI体验:让阅读效率翻倍
人工智能·华为·harmonyos
程序猿追4 小时前
棋盘上的博弈:我在 HarmonyOS 里塞了一个五子棋“大脑”
人工智能·华为·harmonyos
一个假的前端男5 小时前
windows flutter 适配鸿蒙
windows·flutter·harmonyos
程序猿追5 小时前
把 255.255.255.0 拆开看——在 HarmonyOS 上写个 IP 地址与子网掩码计算器
华为·harmonyos
坚果的博客7 小时前
【鸿蒙 PC三方库构建系统】SHA 库 鸿蒙PC 适配详解
华为·harmonyos
seal_jing7 小时前
44岁被裁后用AI写鸿蒙App(3):AGC 认证 + 云函数 + 端到端加密实战
harmonyos
程序猿追9 小时前
画个饼,给数据点颜色看看——在 HarmonyOS 模拟器上手搓一个饼图/环形图组件
深度学习·算法·harmonyos
不爱吃糖的程序媛10 小时前
鸿蒙 6 新华字典实战:从零到一用 ArkTS 开发原生鸿蒙应用
华为·ar·harmonyos