codecamp

鸿蒙OS 页面路由

很多应用由多个页面组成,比如用户可以从音乐列表页面点击歌曲,跳转到该歌曲的播放界面。开发者需要通过页面路由将这些页面串联起来,按需实现跳转。

页面路由 router 根据页面的 uri 来找到目标页面,从而实现跳转。以最基础的两个页面之间的跳转为例,具体实现步骤如下:

  1. 创建两个页面。
  2. 修改配置文件 config.json。
  3. 调用 router.push() 路由到详情页。
  4. 调用 router.back() 回到首页。

创建两个页面

创建 index 和 detail 页面,这两个页面均包含一个 text 组件和 button 组件:text 组件用来指明当前页面,button 组件用来实现两个页面之间的相互跳转。hml 文件代码示例如下:

<!-- index.hml -->
<div class="container">
  <div class="text-div">
    <text class="title">This is the index page.</text>
  </div>
  <div class="button-div">  
    <button type="capsule" value="Go to the second page" onclick="launch"></button>
  </div>
</div>

<!-- detail.hml -->
<div class="container">
  <div class="text-div">
    <text class="title">This is the detail page.</text>
  </div>
  <div class="button-div">  
    <button type="capsule" value="Go back" onclick="launch"></button>
  </div>
</div>

修改配置文件

config.json 文件是配置文件,主要包含了 JS FA 页面路由信息。开发者新创建的页面都要在配置文件的pages 标签中进行注册,处于第一位的页面为首页,即点击图标后的主页面。

{
...
  "pages": [
    "pages/index/index",
    "pages/detail/detail"
  ],
...
}

实现跳转

为了使 button 组件的 launch 方法生效,需要在页面的 js 文件中实现跳转逻辑。调用 router.push() 接口将 uri 指定的页面添加到路由栈中,即跳转到 uri 指定的页面。在调用 router 方法之前,需要导入 router 模块。代码示例如下:

// index.js
import router from '@system.router';
export default {
  launch: function() {
    router.push ({
      uri: 'pages/detail/detail',
    });
  },
}

// detail.js
import router from '@system.router';
export default {
  launch: function() {
    router.back();
  },
}

运行效果如下图所示:

图1 页面路由效果 点击放大

鸿蒙OS 事件
焦点逻辑
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

鸿蒙OS 开发

鸿蒙OS 术语

鸿蒙OS Java API参考

鸿蒙OS ohos.aafwk.ability

鸿蒙OS ohos.aafwk.abilityjet.activedata

鸿蒙OS ohos.aafwk.content

鸿蒙OS java.lang

鸿蒙OS java.Util

鸿蒙OS java.Util class

鸿蒙OS ohos.data.dataability

鸿蒙OS ohos.data.dataability class

鸿蒙OS ohos.agp.components

鸿蒙OS ohos.agp.components interface

鸿蒙OS ohos.agp.components class

鸿蒙OS ohos.global.configuration

鸿蒙OS java.io

鸿蒙OS ohos.data.resultset

鸿蒙OS ohos.data.resultset interface

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }