鴻蒙OS 頁面路由

2020-09-18 13:57 更新

很多應(yīng)用由多個頁面組成,比如用戶可以從音樂列表頁面點擊歌曲,跳轉(zhuǎn)到該歌曲的播放界面。開發(fā)者需要通過頁面路由將這些頁面串聯(lián)起來,按需實現(xiàn)跳轉(zhuǎn)。

頁面路由 router 根據(jù)頁面的 uri 來找到目標頁面,從而實現(xiàn)跳轉(zhuǎn)。以最基礎(chǔ)的兩個頁面之間的跳轉(zhuǎn)為例,具體實現(xiàn)步驟如下:

  1. 創(chuàng)建兩個頁面。
  2. 修改配置文件 config.json。
  3. 調(diào)用 router.push() 路由到詳情頁。
  4. 調(diào)用 router.back() 回到首頁。

創(chuàng)建兩個頁面

創(chuàng)建 index 和 detail 頁面,這兩個頁面均包含一個 text 組件和 button 組件:text 組件用來指明當前頁面,button 組件用來實現(xiàn)兩個頁面之間的相互跳轉(zhuǎn)。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 頁面路由信息。開發(fā)者新創(chuàng)建的頁面都要在配置文件的pages 標簽中進行注冊,處于第一位的頁面為首頁,即點擊圖標后的主頁面。

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

實現(xiàn)跳轉(zhuǎn)

為了使 button 組件的 launch 方法生效,需要在頁面的 js 文件中實現(xiàn)跳轉(zhuǎn)邏輯。調(diào)用 router.push() 接口將 uri 指定的頁面添加到路由棧中,即跳轉(zhuǎn)到 uri 指定的頁面。在調(diào)用 router 方法之前,需要導(dǎo)入 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 頁面路由效果 點擊放大

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號