学习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}`);
          }
        }
      )
    })
  }
}


相关推荐
yngsqq12 分钟前
031集——文本文件按空格分行——C#学习笔记
笔记·学习·c#
zengy539 分钟前
Effective C++中文版学习记录(三)
数据结构·c++·学习·stl
cyt涛1 小时前
MyBatis 学习总结
数据库·sql·学习·mysql·mybatis·jdbc·lombok
Willliam_william1 小时前
SystemC学习(1)— SystemC安装与HelloWorld
学习
sealaugh321 小时前
aws(学习笔记第一课) AWS CLI,创建ec2 server以及drawio进行aws画图
笔记·学习·aws
布丁不叮早起枣祈1 小时前
10.5学习
学习
向上的车轮1 小时前
Django学习笔记五:templates使用详解
笔记·学习·django
蒲公英10013 小时前
vue3学习:axios输入城市名称查询该城市天气
前端·vue.js·学习
训山3 小时前
【11】纯血鸿蒙HarmonyOS NEXT星河版开发0基础学习笔记-模块化语法与自定义组件
笔记·学习·华为·harmonyos·鸿蒙系统
①个程序员3 小时前
thinkphp 学习记录
学习