入門版 鴻蒙 組件導航 (Navigation)
注意:使用 DevEco Studio 運行本案例,要使用模擬器,千萬不要用預覽器,預覽器看看 Navigation 布局還是可以的
- 效果:點擊首頁(Index)跳轉到頁面(MainPage)
- 先寫 Index 和 MainPage 這兩個頁面
- 路由相關配置
Index 和 MainPage 兩個頁面,點擊這個兩個頁面可以互相跳轉
// src/main/ets/pages/Index.ets
@Entry
@Component
struct Index {// 創建導航路徑棧實例,用于管理頁面跳轉歷史pageStack: NavPathStack = new NavPathStack()build() {// 使用Navigation組件作為導航容器,傳入pageStack管理路由Navigation(this.pageStack) {Column() {}.width('100%').height('100%').backgroundColor(Color.Blue).onClick(() => {// 擊時壓入名為"MainPage"的新頁面到路徑棧this.pageStack.pushPathByName("MainPage", null);})}}
}
// src/main/ets/pages/MainPage.ets
// 跳轉頁面入口函數
@Builder
export function MainPageBuilder() {MainPage()
}@Component
struct MainPage {pageStack: NavPathStack = new NavPathStack()build() {// 定義導航目標頁面的容器NavDestination() {}.width('100%').height('100%').backgroundColor(Color.Brown).title('MainPage').onClick(() => {// 清空導航路徑棧(用于返回首頁)this.pageStack.clear()})// 頁面就緒回調onReady.onReady((context: NavDestinationContext) => {// 從上下文中獲取路徑棧實例(需確保與父組件共享同一個實例)this.pageStack = context.pathStack})}
}
路由相關的配置
在跳轉目標模塊的配置文件 module.json5 添加路由表配置
// src/main/module.json5{"module" : {"routerMap": "$profile:route_map"}}
添加完路由配置文件地址后,需要在工程 resources/base/profile 中創建 route_map.json 文件
// src/main/resources/base/profile/router_map.json
{"routerMap": [{"name": "MainPage","pageSourceFile": "src/main/ets/pages/MainPage.ets","buildFunction": "MainPageBuilder","data": {"description": "this is MainPage"}}]
}
// src/main/resources/base/profile/main_pages.json
{"src": ["pages/Index"]
}