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