鸿蒙OS 页面路由

2020-09-18 13:57 更新

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

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

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

创建两个页面

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

  1. <!-- index.hml -->
  2. <div class="container">
  3. <div class="text-div">
  4. <text class="title">This is the index page.</text>
  5. </div>
  6. <div class="button-div">
  7. <button type="capsule" value="Go to the second page" onclick="launch"></button>
  8. </div>
  9. </div>

  1. <!-- detail.hml -->
  2. <div class="container">
  3. <div class="text-div">
  4. <text class="title">This is the detail page.</text>
  5. </div>
  6. <div class="button-div">
  7. <button type="capsule" value="Go back" onclick="launch"></button>
  8. </div>
  9. </div>

修改配置文件

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

  1. {
  2. ...
  3. "pages": [
  4. "pages/index/index",
  5. "pages/detail/detail"
  6. ],
  7. ...
  8. }

实现跳转

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

  1. // index.js
  2. import router from '@system.router';
  3. export default {
  4. launch: function() {
  5. router.push ({
  6. uri: 'pages/detail/detail',
  7. });
  8. },
  9. }

  1. // detail.js
  2. import router from '@system.router';
  3. export default {
  4. launch: function() {
  5. router.back();
  6. },
  7. }

运行效果如下图所示:

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

以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号