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

运行效果图如下:

相关推荐
奶糖不太甜4 分钟前
鸿蒙开发问题之纯血鸿蒙自启动步骤详解
harmonyos
xq95275 小时前
鸿蒙next 获取versionCode和versionName
harmonyos
鸿蒙小白龙6 小时前
openharmony之恢复出厂设置需求总结
harmonyos·鸿蒙·鸿蒙系统
深海的鲸同学 luvi6 小时前
【HarmonyOS】H5 实现在浏览器中正常跳转 AppLinking 至应用
华为·harmonyos
zhanshuo18 小时前
HarmonyOS 实战:学会在鸿蒙中使用第三方 JavaScript 库(附完整 Demo)
harmonyos
zhanshuo18 小时前
鸿蒙应用权限处理全攻略:从配置到相机拍照,一篇文章讲透
harmonyos
AlbertZein20 小时前
HarmonyOS5 凭什么学鸿蒙—— GetContext
架构·harmonyos
森之鸟1 天前
flutter项目适配鸿蒙
flutter·华为·harmonyos
奶糖不太甜1 天前
鸿蒙图片资源加载全攻略:从基础到性能优化
harmonyos·图片资源
小小小小小星1 天前
鸿蒙多端适配开发指南:从入门到实战
harmonyos