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 小时前
Electron for鸿蒙PC开发的骰子游戏应用
游戏·electron·harmonyos
春卷同学1 小时前
Electron for 鸿蒙pc开发的二十一点游戏
游戏·electron·harmonyos
不老刘2 小时前
react native for OpenHarmony iconfont 图标不显示问题
react native·harmonyos·iconfont
汉堡黄•᷄ࡇ•᷅2 小时前
鸿蒙开发: 案例集合List:ListItem侧滑(删除、收藏)
harmonyos·鸿蒙·鸿蒙系统
春卷同学3 小时前
拼图游戏 - Electron for 鸿蒙PC项目实战案例
javascript·electron·harmonyos
春卷同学3 小时前
基于 Electron 开发的跨平台鸿蒙PC端数字猜谜游戏桌面应用
游戏·electron·harmonyos
盐焗西兰花3 小时前
鸿蒙学习实战之路 - 轮播图组件实现
学习·华为·harmonyos
ChinaDragon3 小时前
HarmonyOS:转场动画
harmonyos
ChinaDragon3 小时前
HarmonyOS:转场动画-模态转场
harmonyos
青云交3 小时前
ShellCheck命令行工具适配开源鸿蒙PC实战指南
华为·开源·makefile·harmonyos·shellcheck·预编译二进制·hnp 打包