在应用程序开发中,页面路由起着至关重要的作用,它负责在不同页面间实现顺畅的跳转和数据传递。HarmonyOS为此提供了强大的Router模块,借助URL地址,开发者可以便捷地进行页面路由操作,轻松访问应用程序的各个页面。本文将围绕页面跳转、页面返回以及在页面返回前增加询问框这三个方面,详细介绍Router模块所具备的功能。

一、页面跳转

页面跳转是应用开发中的常见需求,它不仅涉及从一个页面过渡到另一个页面,有时还需在跳转过程中传递数据。HarmonyOS Router模块提供了router.pushUrl()和router.replaceUrl()两种跳转模式,以满足不同的应用场景。

  1. router.pushUrl():将目标页压入页面栈,保留当前页状态。用户可通过返回键或调用router.back()方法返回至当前页。页面栈最大容量为32个页面,若超出,可使用router.clear()方法清理历史记录,释放内存。
  2. router.replaceUrl():用目标页替换当前页并销毁之,无法返回。此模式适用于需要释放当前页资源且返回时直接退出应用的场景。

此外,Router模块还支持Standard和Single两种实例模式,以决定目标URL是否对应多个实例。

  • Standard模式(默认):每次调用均创建新的目标页并压入栈顶。
  • Single模式:确保同一URL仅存在一个实例。已存在同URL页面时,将其移至栈顶并重新加载;不存在则按Standard模式跳转。

使用Router模块前,需先导入:

import router from '@ohos.router';

HarmonyOS入门之路由管理_页面跳转

场景示例:

场景一:从主页(Home)跳转至详情页(Detail),保留主页状态以便返回。选用pushUrl()与Standard模式(或省略)。

// Home页面
function onJumpClick(): void {
  router.pushUrl({
    url: 'pages/Detail'
  }, router.RouterMode.Standard, (err) => {
    if (err) {
      console.error(`Invoke pushUrl failed, code is ${err.code}, message is ${err.message}`);
      return;
    }
    console.info('Invoke pushUrl succeeded.');
  });
}


场景二:从登录页(Login)跳转至个人中心页(Profile),销毁登录页且返回时直接退出应用。选用replaceUrl()与Standard模式(或省略)。

// Login页面
function onJumpClick(): void {
  router.replaceUrl({
    url: 'pages/Profile'
  }, router.RouterMode.Standard, (err) => {
    if (err) {
      console.error(`Invoke replaceUrl failed, code is ${err.code}, message is ${err.message}`);
      return;
    }
    console.info('Invoke replaceUrl succeeded.');
  });
}

场景三:从设置页(Setting)跳转至主题切换页(Theme),确保栈中仅有一个主题切换页,返回直达设置页。选用pushUrl()与Single模式。

// Setting页面
function onJumpClick(): void {
  router.pushUrl({
    url: 'pages/Theme'
  }, router.RouterMode.Single, (err) => {
    if (err) {
      console.error(`Invoke pushUrl failed, code is ${err.code}, message is ${err.message}`);
      return;
    }
    console.info('Invoke pushUrl succeeded.');
  });
}

场景四:从搜索结果列表页(SearchResult)跳转至搜索结果详情页(SearchDetail),如已查看过,直接跳转至已存在详情页。选用replaceUrl()与Single模式。

// SearchResult页面
function onJumpClick(): void {
  router.replaceUrl({
    url: 'pages/SearchDetail'
  }, router.RouterMode.Single, (err) => {
    if (err) {
      console.error(`Invoke replaceUrl failed, code is ${err.code}, message is ${err.message}`);
      return;
    }
    console.info('Invoke replaceUrl succeeded.');
  });
}

数据传递:在跳转时传递数据给目标页,只需在调用Router方法时添加params属性,指定一个对象作为参数。目标页通过调用router.getParams()获取传递参数。

二、页面返回

用户完成操作后,往往需要返回上一页面或指定页面,此时需借助页面返回功能。返回过程中,可能需要向目标页传递数据。

返回方式

  1. 返回至上一页面router.back()。仅当上一页面存在于页面栈中时有效。
  2. 返回至指定页面router.back({ url: 'pages/Home' })。目标页须在页面栈中。
  3. 返回至指定页面并传递参数router.back({ url: 'pages/Home', params: { info: '来自Home页' } })。目标页通过router.getParams()获取参数。

HarmonyOS入门之路由管理_页面跳转_02

三、页面返回前增加询问框

为避免用户误操作或丢失数据,有时需在返回前弹出询问框,确认用户操作意愿。

系统默认询问框:使用router.showAlertBeforeBackPage()设置询问框信息,然后调用router.back()实现返回。

function onBackClick(): void {
  try {
    router.showAlertBeforeBackPage({
      message: '您还没有完成支付,确定要返回吗?'
    });
  } catch (err) {
    console.error(`Invoke showAlertBeforeBackPage failed, code is ${err.code}, message is ${err.message}`);
  }

  router.back();
}

自定义询问框:利用弹窗组件(如promptAction)实现自定义样式询问框。用户点击“确认”时调用router.back()

function onBackClick() {
  promptAction.showDialog({
    message: '您还没有完成支付,确定要返回吗?',
    buttons: [
      { text: '取消', color: '#FF0000' },
      { text: '确认', color: '#0099FF' }
    ]
  }).then((result) => {
    if (result.index === 0) {
      console.info('User canceled the operation.');
    } else if (result.index === 1) {
      console.info('User confirmed the operation.');
      router.back();
    }
  }).catch((err) => {
    console.error(`Invoke showDialog failed, code is ${err.code}, message is ${err.message}`);
  });
}

HarmonyOS入门之路由管理_Harmony_03

综上所述,HarmonyOS Router模块为开发者提供了丰富而灵活的页面路由功能,包括页面跳转、页面返回以及返回前询问框,助力构建高效、用户友好的应用程序。