HarmonyOS4 页面路由

发布于:2024-04-14 ⋅ 阅读:(149) ⋅ 点赞:(0)

Index.ets:

import router from '@ohos.router'

class RouterInfo {
  // 页面路径
  url: string
  // 页面标题
  title: string

  constructor(url: string, title: string) {
    this.url = url
    this.title = title
  }
}

@Entry // 入口組件
@Component
struct Index {
  @State message: string = '页面列表'

  // 路由列表数组
  private routers: RouterInfo[] = [
    // app Log: 路由失败, errorCode: 100002 errMsg:Uri error. The uri of router is not exist.
    // main_pages.json配置
    new RouterInfo('pages/ImagePage', '图片查看案例'),
    new RouterInfo('pages/PropPage', '任务列表案例')
  ]

  build() {

    Column() {
      Text(this.message)
        .fontSize(50)
        .fontWeight(FontWeight.Bold)
        .height(80)
        .onClick(() => {
          this.message = 'Hello ArkTS!';
        })

      List({ space: 15 }) {
        ForEach(
          this.routers,
          (router, index) => {
            ListItem() {
              this.RouterItem(router, index + 1)
            }
          }
        )
      }
      .layoutWeight(1)
      .alignListItem(ListItemAlign.Center)
      .width('100%')
    }
    .width('100%')
    .height('100%')
  }

  @Builder
  RouterItem(r: RouterInfo, i: number) {
    Row() {
      Text(i + '.')
        .fontSize(20)
        .fontColor(Color.White)
      Blank()
      Text(r.title)
        .fontSize(20)
        .fontColor(Color.White)
    }
    .width('90%')
    .padding(12)
    .backgroundColor('#38f')
    .borderRadius(20)
    .shadow({radius: 6, color: '#4F000000', offsetX: 2, offsetY: 2})
    .onClick(() => {
      // router跳转
      router.pushUrl(
        {
        url: r.url,
        params: {id: i}
        },
        router.RouterMode.Single,
        err => {
          if (err) {
            console.log(`路由失败, errorCode: ${err.code} errMsg:${err.message}`)
          }
        }
      )
    })
  }
}

/**
 * struct:自定义组件 可复用的UI单元
 * 装饰器:用来装饰类结构、方法、变量
 * @Component:标记自定义组件
 * @Entry:标记当前组件是入口组件
 * @State:标记一个变量是状态变量,值变化时会触发UI更新
 * build():UI描述,其内部以声明式方式描述UI结构
 * 内置组件:ArkUI提供的组件,比如容器组件如Row、Column
 * 基础组件:自带样式和功能的页面元素,如Text
 * 属性方法:设置组件的UI样式
 * 事件方法:设置组件的事件回调
 * 组件通用属性、特有属性(图片插值)
 */


网站公告

今日签到

点亮在社区的每一天
去签到