优秀的编程知识分享平台

网站首页 > 技术文章 正文

鸿蒙开发(一百三十三):router 页面启动模式

nanyue 2024-08-11 20:39:32 技术文章 8 ℃

既然页面栈最大容量为 32,容量有限,那么我们在启动页面的时候尽量做到节省资源消耗,怎么做呢?

可以从页面的启动模式入手。

Router 模块提供了两种页面启动模式,分别是 Standard 和 Single。

这两种模式决定了目标 url 是否会对应多个实例。

  • Standard:多实例模式,也是默认情况下的跳转模式。目标页面会被添加到页面栈顶,无论栈中是否存在相同 url 的页面。
  • Single:单实例模式。如果目标页面的 url 已经存在于页面栈中,则会将离栈顶最近的同 url 页面移动到栈顶,该页面成为新建页。如果目标页面的 url 在页面栈中不存在同 url 页面,则按照默认的多实例模式进行跳转。

接下来,分别就 Standard 和 Single 进行演示。

Standard

首先,编写 Index 页面。

import router from '@ohos.router';

@Entry
@Component
struct Index {
  onPageShow() {
    // 输出当前页面栈里面的数量
    console.log(router.getLength())
  }

  build() {
    Column() {
      Text("第一页")
        .fontSize(30)

      Button("跳转到第二页")
        .onClick(() => {
          router.pushUrl({ url: "pages/Second" }, router.RouterMode.Standard)
        })
    }
  }
}

关键技术点:

  1. 在 onPageShow 生命周期函数中输出页面栈数量。
  2. 在点击事件中,使用 pushUrl 跳转页面,并指定页面启动模式为 router.RouterMode.Standard。

然后,编写 Second 页面。

import router from '@ohos.router';

@Entry
@Component
struct Second {
  onPageShow() {
    // 输出当前页面栈里面的数量
    console.log(router.getLength())
  }

  build() {
    Column() {
      Text("第二页")
        .fontSize(30)

      Button("跳转至第三页")
        .onClick(() => {
          router.pushUrl({ url: "pages/Third" }, router.RouterMode.Standard)
        })
    }
  }
}

最后,编写 Third 页面。

import router from '@ohos.router'

@Entry
@Component
struct Third {
  onPageShow() {
    // 输出当前页面栈里面的数量
    console.log(router.getLength())
  }

  build() {
    Column() {
      Text("第三页")
        .fontSize(30)

      Button("跳转到第一页")
        .onClick(() => {
          router.pushUrl({ url: "pages/Index" }, router.RouterMode.Standard)
        })
    }
  }
}

运行结果:

控制台输出:

1
2
3
4

从运行结果来看,Index->Second->Third->Index,一共创建了四个页面。

Single

将上述示例代码中所有页面跳转的代码:

router.pushUrl({ url: "pages/Index" }, router.RouterMode.Standard)

改为:

router.pushUrl({ url: "pages/Index" }, router.RouterMode.Single)

运行结果:

控制台输出:

1
2
3
3

从运行结果来看,Index->Second->Third->Index。在 Single 启动模式下,一共只创建了 三个页面。因为这些页面只会在页面栈里存在一份,所以从 Thrid 页面跳转到 Index 页面时,查询到页面栈里已存在 Index 页面,直接将 Index 移到了栈顶。

综上所述,Standard 和 Single 这两种模式决定了目标 url 是否会对应多个实例

Tags:

最近发表
标签列表