• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Page Routing
2
3> **NOTE**
4>
5> - The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
6> - Page routing APIs can be invoked only after page rendering is complete. Do not call the APIs in **onInit** and **onReady** when the page is still in the rendering phase.
7
8## Modules to Import
9
10```
11import router from '@ohos.router'
12```
13
14## Required Permissions
15
16None.
17
18## router.push
19
20push(options: RouterOptions): void
21
22Navigates to a specified page in the application.
23
24**System capability**: SystemCapability.ArkUI.ArkUI.Full
25
26**Parameters**
27| Name| Type| Mandatory| Description|
28| -------- | -------- | -------- | -------- |
29| options | [RouterOptions](#routeroptions) | Yes| Page routing parameters.|
30
31
32**Example**
33  ```js
34  // Current page
35  export default {
36    pushPage() {
37      router.push({
38        url: 'pages/routerpage2/routerpage2',
39        params: {
40  	data1: 'message',
41          data2: {
42            data3: [123, 456, 789]
43  	},
44        },
45      });
46    }
47  }
48  ```
49  ```js
50  // routerpage2 page
51  export default {
52    data: {
53      data1: 'default',
54      data2: {
55        data3: [1, 2, 3]
56      }
57    },
58    onInit() {
59      console.info('showData1:' + this.data1);
60      console.info('showData3:' + this.data2.data3);
61    }
62  }
63  ```
64
65
66## router.replace
67
68replace(options: RouterOptions): void
69
70Replaces the current page with another one in the application and destroys the current page.
71
72**System capability**: SystemCapability.ArkUI.ArkUI.Full
73
74**Parameters**
75| Name| Type| Mandatory| Description|
76| -------- | -------- | -------- | -------- |
77| options | [RouterOptions](#routeroptions) | Yes| Description of the new page.|
78
79**Example**
80
81  ```js
82  // Current page
83  export default {
84    replacePage() {
85      router.replace({
86        url: 'pages/detail/detail',
87        params: {
88          data1: 'message',
89        },
90      });
91    }
92  }
93  ```
94
95  ```js
96  // detail page
97  export default {
98    data: {
99      data1: 'default'
100    },
101    onInit() {
102      console.info('showData1:' + this.data1)
103    }
104  }
105  ```
106
107## router.back
108
109back(options?: RouterOptions ): void
110
111Returns to the previous page or a specified page.
112
113**System capability**: SystemCapability.ArkUI.ArkUI.Full
114
115**Parameters**
116| Name| Type| Mandatory| Description|
117| -------- | -------- | -------- | -------- |
118| options | [RouterOptions](#routeroptions) | Yes| Description of the page. The **url** parameter indicates the URL of the page to return to. If the specified page does not exist in the page stack, the application does not respond. If no URL is set, the previous page is returned, and the page in the page stack is not reclaimed. It will be reclaimed after being popped up.|
119
120**Example**
121  ```js
122  // index page
123  export default {
124    indexPushPage() {
125      router.push({
126        url: 'pages/detail/detail',
127      });
128    }
129  }
130  ```
131
132  ```js
133  // detail page
134  export default {
135    detailPushPage() {
136      router.push({
137        url: 'pages/mall/mall',
138      });
139    }
140  }
141  ```
142
143  ```js
144  // Navigate from the mall page to the detail page through router.back().
145  export default {
146    mallBackPage() {
147      router.back();
148    }
149  }
150  ```
151
152  ```js
153  // Navigate from the detail page to the index page through router.back().
154  export default {
155    defaultBack() {
156      router.back();
157    }
158  }
159  ```
160
161  ```js
162  // Return to the detail page through router.back().
163  export default {
164    backToDetail() {
165      router.back({url:'pages/detail/detail'});
166    }
167  }
168  ```
169
170## router.clear
171
172clear(): void
173
174Clears all historical pages in the stack and retains only the current page at the top of the stack.
175
176**System capability**: SystemCapability.ArkUI.ArkUI.Full
177
178**Example**
179  ```js
180  export default {
181    clearPage() {
182      router.clear();
183    }
184  }js
185  ```
186
187## router.getLength
188
189getLength(): string
190
191Obtains the number of pages in the current stack.
192
193**System capability**: SystemCapability.ArkUI.ArkUI.Full
194
195**Return value**
196| Type| Description|
197| -------- | -------- |
198| string | Number of pages in the stack. The maximum value is **32**.|
199
200**Example**
201  ```js
202  export default {
203    getLength() {
204      var size = router.getLength();
205      console.log('pages stack size = ' + size);
206    }
207  }
208  ```
209
210## router.getState
211
212getState(): RouterState
213
214Obtains state information about the current page.
215
216**System capability**: SystemCapability.ArkUI.ArkUI.Full
217
218**Return value**
219
220| Type                       | Description          |
221| --------------------------- | -------------- |
222| [RouterState](#routerstate) | Page routing state.|
223## RouterState
224Describes the page routing state.
225
226**System capability**: SystemCapability.ArkUI.ArkUI.Full
227
228| Name| Type| Description|
229| -------- | -------- | -------- |
230| index | number | Index of the current page in the stack.<br>>&nbsp;![icon-note.gif](public_sys-resources/icon-note.gif)&nbsp;**NOTE**<br>>&nbsp;The index starts from 1 from the bottom to the top of the stack.|
231| name | string | Name of the current page, that is, the file name.|
232| path | string | Path of the current page.|
233
234**Example**
235  ```js
236  export default {
237    getState() {
238      var page = router.getState();
239      console.log('current index = ' + page.index);
240      console.log('current name = ' + page.name);
241      console.log('current path = ' + page.path);
242    }
243  }
244  ```
245
246## router.enableAlertBeforeBackPage
247
248enableAlertBeforeBackPage(options: EnableAlertOptions): void
249
250Enables the display of a confirm dialog box before returning to the previous page.
251
252**System capability**: SystemCapability.ArkUI.ArkUI.Full
253
254**Parameters**
255| Name| Type| Mandatory| Description|
256| -------- | -------- | -------- | -------- |
257| options | [EnableAlertOptions](#enablealertoptions) | Yes| Description of the dialog box.|
258
259**Example**
260
261  ```js
262  export default {
263    enableAlertBeforeBackPage() {
264      router.enableAlertBeforeBackPage({
265        message: 'Message Info',
266      });
267    }
268  }
269  ```
270## EnableAlertOptions
271
272Describes the confirm dialog box.
273
274**System capability**: SystemCapability.ArkUI.ArkUI.Full
275
276| Name| Type| Mandatory| Description|
277| -------- | -------- | -------- | -------- |
278| message | string | Yes| Content displayed in the confirm dialog box.|
279
280## router.disableAlertBeforeBackPage
281
282disableAlertBeforeBackPage(): void
283
284Disables the display of a confirm dialog box before returning to the previous page.
285
286**System capability**: SystemCapability.ArkUI.ArkUI.Full
287
288**Example**
289  ```js
290  export default {
291    disableAlertBeforeBackPage() {
292      router.disableAlertBeforeBackPage();
293    }
294  }
295  ```
296
297##  router.getParams
298
299getParams(): Object
300
301Obtains the parameters passed from the page that initiates redirection to the current page.
302
303**System capability**: SystemCapability.ArkUI.ArkUI.Full
304
305**Return value**
306
307| Type  | Description                              |
308| ------ | ---------------------------------- |
309| Object | Parameters passed from the page that initiates redirection to the current page.|
310
311**Example**
312
313- Web-like example
314  ```js
315  // Current page
316  export default {
317    pushPage() {
318      router.push({
319        url: 'pages/detail/detail',
320        params: {
321          data1: 'message',
322        },
323      });
324    }
325  }
326  ```
327  ```js
328  // detail page
329  export default {
330    onInit() {
331      console.info('showData1:' + router.getParams()[data1]);
332    }
333  }
334  ```
335
336- Declarative example
337
338  ```ts
339  // Navigate to the target page through router.push with the params parameter carried.
340  import router from '@ohos.router'
341
342  @Entry
343  @Component
344  struct Index {
345    async  routePage() {
346      let options = {
347        url: 'pages/second',
348        params: {
349          text: 'This is the value on the first page.',
350          data: {
351            array: [12, 45, 78]
352          },
353        }
354      }
355      try {
356        await router.push(options)
357      } catch (err) {
358        console.info(` fail callback, code: ${err.code}, msg: ${err.msg}`)
359      }
360    }
361
362    build() {
363      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
364          Text('This is the first page.')
365            .fontSize(50)
366            .fontWeight(FontWeight.Bold)
367        Button() {
368          Text('next page')
369            .fontSize(25)
370            .fontWeight(FontWeight.Bold)
371        }.type(ButtonType.Capsule)
372            .margin({ top: 20 })
373            .backgroundColor('#ccc')
374            .onClick(() => {
375              this.routePage()
376        })
377      }
378      .width('100%')
379      .height('100%')
380    }
381  }
382  ```
383
384  ```ts
385  // Receive the transferred parameters on the second page.
386  import router from '@ohos.router'
387
388  @Entry
389  @Component
390  struct Second {
391    private content: string = "This is the second page."
392    @State text: string = router.getParams()['text']
393    @State data: any = router.getParams()['data']
394    @State secondData : string = ''
395
396    build() {
397      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
398        Text(`${this.content}`)
399          .fontSize(50)
400          .fontWeight(FontWeight.Bold)
401        Text(this.text)
402          .fontSize(30)
403          .onClick(()=>{
404            this.secondData = (this.data.array[1]).toString()
405          })
406        .margin({top:20})
407        Text('Value from the first page '+'' + this.secondData)
408          .fontSize(20)
409          .margin({top:20})
410          .backgroundColor('red')
411      }
412      .width('100%')
413      .height('100%')
414    }
415  }
416  ```
417
418## RouterOptions
419
420Describes the page routing options.
421
422**System capability**: SystemCapability.ArkUI.ArkUI.Lite
423
424| Name| Type| Mandatory| Description|
425| -------- | -------- | -------- | -------- |
426| url | string | Yes| URI of the destination page, in either of the following formats:<br>-&nbsp; Absolute path of the page. The value is available in the pages list in the config.json file, for example:<br>&nbsp;&nbsp;-&nbsp;pages/index/index<br>&nbsp;&nbsp;-&nbsp;pages/detail/detail<br>-&nbsp; Particular path. If the URI is a slash (/), the home page is displayed.|
427| params | Object | No| Data that needs to be passed to the destination page during redirection. After the destination page is displayed, it can use the passed data, for example, **this.data1** (**data1** is a key in **params**). If there is the same key (for example, **data1**) on the destination page, the passed **data1** value will replace the original value on the destination page.|
428
429
430  > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
431  >
432  > The page routing stack supports a maximum of 32 pages.
433