ui-js-building-ui-routes.md 2.5 KB
Newer Older
Z
zengyawen 已提交
1
# 页面路由
M
mamingshuai 已提交
2 3 4

很多应用由多个页面组成,比如用户可以从音乐列表页面点击歌曲,跳转到该歌曲的播放界面。开发者需要通过页面路由将这些页面串联起来,按需实现跳转。

Z
zengyawen 已提交
5

Z
zengyawen 已提交
6
页面路由router根据页面的uri找到目标页面,从而实现跳转。以最基础的两个页面之间的跳转为例,具体实现步骤如下:
M
mamingshuai 已提交
7 8


W
wangshuainan 已提交
9
1. 在“Project“窗口,打开src > main >js >MainAbility,右键点击pages文件夹,选择NewJS Page,创建一个详情页。
Z
zengyawen 已提交
10 11 12 13 14 15 16

2. 调用router.push()路由到详情页。

3. 调用router.back()回到首页。


## 构建页面布局
M
mamingshuai 已提交
17 18 19

index和detail这两个页面均包含一个text组件和button组件:text组件用来指明当前页面,button组件用来实现两个页面之间的相互跳转。hml文件代码示例如下:

H
HelloCrease 已提交
20
```html
M
mamingshuai 已提交
21 22 23 24 25 26 27
<!-- index.hml -->
<div class="container">
  <text class="title">This is the index page.</text>
  <button type="capsule" value="Go to the second page" class="button" onclick="launch"></button>
</div>
```

H
HelloCrease 已提交
28
```html
M
mamingshuai 已提交
29 30 31 32 33 34 35
<!-- detail.hml -->
<div class="container">
  <text class="title">This is the detail page.</text>
  <button type="capsule" value="Go back" class="button" onclick="launch"></button>
</div>
```

Z
zengyawen 已提交
36 37

## 构建页面样式
M
mamingshuai 已提交
38 39 40

构建index和detail页面的页面样式,text组件和button组件居中显示,两个组件之间间距为50px。css代码如下(两个页面样式代码一致):

H
HelloCrease 已提交
41
```css
M
mamingshuai 已提交
42 43 44
/* index.css */
/* detail.css */
.container {
W
wangshuainan 已提交
45 46
  width: 100%;
  height: 100%;
M
mamingshuai 已提交
47 48 49 50 51 52 53 54 55 56 57
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.title {
  font-size: 50px;
  margin-bottom: 50px;
}
```


Z
zengyawen 已提交
58 59 60
## 实现跳转

为了使button组件的launch方法生效,需要在页面的js文件中实现跳转逻辑。调用router.push()接口将uri指定的页面添加到路由栈中,即跳转到uri指定的页面。在调用router方法之前,需要导入router模块。代码示例如下:
M
mamingshuai 已提交
61

H
HelloCrease 已提交
62
```js
M
mamingshuai 已提交
63
// index.js
W
wangshuainan 已提交
64
import router from '@ohos.router';
M
mamingshuai 已提交
65 66 67
export default {
  launch() {
    router.push ({
W
wangshuainan 已提交
68
      url: 'pages/detail/detail',
M
mamingshuai 已提交
69 70 71 72 73
    });
  },
}
```

H
HelloCrease 已提交
74
```js
M
mamingshuai 已提交
75
// detail.js
W
wangshuainan 已提交
76
import router from '@ohos.router';
M
mamingshuai 已提交
77 78 79 80 81 82 83 84 85
export default {
  launch() {
    router.back();
  },
}
```

运行效果如下图所示:

Z
zengyawen 已提交
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/monthly_20221018/UI/JsRouter)