学习ArkTS --页面路由

页面路由 router

页面路由是指在应用程序中实现不同页面之间的跳转和数据传递。

页面栈的最大容量上限为32个页面,使用router.clear()方法可以清空页面栈,释放内存。

Router有两种页面跳转模式,分别是:

  1. router.pushUrl():目标页不会替换当前页面,而是压入页面栈,因此可以用router.back()返回当前页
  2. router.replaceUrl(): 目标替换当前页面,当前页会被销毁并释放资源,无法返回当前页。

Router有两种页面实例模式,分别是:

  1. standard: 标准实例模式,每次跳转都会新建一个目标页并压入栈顶。默认就是这种模式。
  2. Single: 单实例模式,如果目标页面已经在栈中,则离栈顶最近的同Url页面会被移动到栈顶并重新加载
复制代码
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[] = [
    new RouterInfo('pages/Imagepage','图片查看案例'),
    new RouterInfo('pages/ItemPages','商品烈表案例'),
    new RouterInfo('pages/StatePage','jack案例'),
    new RouterInfo('pages/ProPage','任务列表案例')
]
  build(){
    Column() {
      Text(this.message)
        .fontSize(50)
        .fontWeight(FontWeight.Bold)
        .height(80)
        .onClick(() =>{
          router.back() // 返回上一页
        })

      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)
        .fontColor(Color.White)
        .fontSize(20)
    }
    .width('90%')
    .padding(12)
    .backgroundColor('#38f')
    .borderRadius(20)
    .shadow({radius: 6, color: '#4F000000', offsetX: 2, offsetY: 4})
    .onClick(() => {
      router.pushUrl(
        {
          url:r.url,
          params: {id: i}
        },
        router.RouterMode.Single,
        err => {
          if (err){
            console.log(`路由失败, errorCode: ${err.code} errMsg:${err.message}`);
          }
        }
      )
    })
  }
}


相关推荐
通信小呆呆3 天前
当算法有了“五感”:多模态数据融合如何向人体感官协同学习?
人工智能·学习·算法·机器学习·机器人
H__Rick3 天前
自动对焦学习-3
人工智能·学习·计算机视觉
Daisy Lee3 天前
量化学习-第1章-什么是量化金融
学习·金融·datawhale
Alsn863 天前
等待学习-学习目录:Docker 容器安全攻防
学习·安全·docker
YM52e3 天前
买菜计算器小应用 - HarmonyOS ArkUI 开发实战-PC版本
学习·华为·harmonyos·鸿蒙·鸿蒙系统
小雨下雨的雨3 天前
HarmonyOS ArkUI训练营入门-组件掌握系列-Animation 动画效果实现-PC版本
学习·华为·harmonyos·鸿蒙
cqbzcsq3 天前
CellFlow虚拟细胞论文阅读
论文阅读·人工智能·笔记·学习·生物信息
YangYang9YangYan3 天前
2026初入职场学习数据分析的价值
学习·数据挖掘·数据分析
guslegend3 天前
理论学习:什么是 Coding Agent?
学习
自传.3 天前
尚硅谷 Vibe Coding|第三章(1) Claude Code深度使用与进阶技巧 学习笔记
笔记·学习·尚硅谷·vibecoding