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