• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# 页面路由
2
3很多应用由多个页面组成,比如用户可以从音乐列表页面点击歌曲,跳转到该歌曲的播放界面。开发者需要通过页面路由将这些页面串联起来,按需实现跳转。
4
5
6页面路由router根据页面的uri找到目标页面,从而实现跳转。以最基础的两个页面之间的跳转为例,具体实现步骤如下:
7
8
91. 在“Project“窗口,打开src > main >js >MainAbility,右键点击pages文件夹,选择NewJS Page,创建一个详情页。
10
112. 调用router.push()路由到详情页。
12
133. 调用router.back()回到首页。
14
15
16## 构建页面布局
17
18index和detail这两个页面均包含一个text组件和button组件:text组件用来指明当前页面,button组件用来实现两个页面之间的相互跳转。hml文件代码示例如下:
19
20```html
21<!-- index.hml -->
22<div class="container">
23  <text class="title">This is the index page.</text>
24  <button type="capsule" value="Go to the second page" class="button" onclick="launch"></button>
25</div>
26```
27
28```html
29<!-- detail.hml -->
30<div class="container">
31  <text class="title">This is the detail page.</text>
32  <button type="capsule" value="Go back" class="button" onclick="launch"></button>
33</div>
34```
35
36
37## 构建页面样式
38
39构建index和detail页面的页面样式,text组件和button组件居中显示,两个组件之间间距为50px。css代码如下(两个页面样式代码一致):
40
41```css
42/* index.css */
43/* detail.css */
44.container {
45  width: 100%;
46  height: 100%;
47  flex-direction: column;
48  justify-content: center;
49  align-items: center;
50}
51.title {
52  font-size: 50px;
53  margin-bottom: 50px;
54}
55```
56
57
58## 实现跳转
59
60为了使button组件的launch方法生效,需要在页面的js文件中实现跳转逻辑。调用router.push()接口将uri指定的页面添加到路由栈中,即跳转到uri指定的页面。在调用router方法之前,需要导入router模块。代码示例如下:
61
62```js
63// index.js
64import router from '@ohos.router';
65export default {
66  launch() {
67    router.push ({
68      url: 'pages/detail/detail',
69    });
70  },
71}
72```
73
74```js
75// detail.js
76import router from '@ohos.router';
77export default {
78  launch() {
79    router.back();
80  },
81}
82```
83
84运行效果如下图所示:
85
86![zh-cn_image_0000001070707559](figures/zh-cn_image_0000001070707559.png)
87
88
89## 相关实例
90
91针对页面路由开发,有以下相关实例可供参考:
92
93- [`JsRouter`:页面路由(JS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/OpenHarmony-3.2-Release/UI/JsRouter)
94