js-apis-router.md 11.2 KB
Newer Older
W
wusongqing 已提交
1 2
# Page Routing

W
wusongqing 已提交
3 4
The **Router** module provides APIs to access pages through URLs. You can use the APIs to navigate to a specified page in an application, replace the current page with another one in an application, and return to the previous page or a specified page.

W
wusongqing 已提交
5
> **NOTE**
W
wusongqing 已提交
6 7
>
> - 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.
W
wusongqing 已提交
8
>
W
wusongqing 已提交
9
> - Page routing APIs can be invoked only after page rendering is complete. Do not call these APIs in **onInit** and **onReady** when the page is still in the rendering phase.
W
wusongqing 已提交
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

## Modules to Import

```
import router from '@ohos.router'
```

## router.push

push(options: RouterOptions): void

Navigates to a specified page in the application.

**System capability**: SystemCapability.ArkUI.ArkUI.Full

**Parameters**
W
wusongqing 已提交
26 27 28
| Name    | Type                             | Mandatory  | Description       |
| ------- | ------------------------------- | ---- | --------- |
| options | [RouterOptions](#routeroptions) | Yes   | Page routing parameters.|
W
wusongqing 已提交
29 30 31


**Example**
W
wusongqing 已提交
32
```js
W
wusongqing 已提交
33 34 35 36 37 38 39 40 41
router.push({
  url: 'pages/routerpage2',
  params: {
    data1: 'message',
    data2: {
      data3: [123, 456, 789]
    },
  },
});
W
wusongqing 已提交
42
```
W
wusongqing 已提交
43 44 45 46 47 48 49 50 51
## router.push<sup>9+</sup>

push(options: RouterOptions, mode: RouterMode): void

Navigates to a specified page in the application.

**System capability**: SystemCapability.ArkUI.ArkUI.Full

**Parameters**
W
wusongqing 已提交
52 53 54 55
| Name    | Type                             | Mandatory  | Description        |
| ------- | ------------------------------- | ---- | ---------- |
| options | [RouterOptions](#routeroptions) | Yes   | Page routing parameters. |
| mode    | [RouterMode](#routermode9)      | Yes   | Routing mode.|
W
wusongqing 已提交
56 57 58


**Example**
W
wusongqing 已提交
59
```js
W
wusongqing 已提交
60 61 62 63 64 65
router.push({
  url: 'pages/routerpage2/routerpage2',
  params: {
    data1: 'message',
    data2: {
      data3: [123, 456, 789]
W
wusongqing 已提交
66
    },
W
wusongqing 已提交
67 68
  },
},router.RouterMode.Standard);
W
wusongqing 已提交
69
```
W
wusongqing 已提交
70 71 72

## router.replace

W
wusongqing 已提交
73
replace(options: RouterOptions): void
W
wusongqing 已提交
74 75 76 77 78 79

Replaces the current page with another one in the application and destroys the current page.

**System capability**: SystemCapability.ArkUI.ArkUI.Full

**Parameters**
W
wusongqing 已提交
80

W
wusongqing 已提交
81 82 83
| Name | Type                           | Mandatory| Description              |
| ------- | ------------------------------- | ---- | ------------------ |
| options | [RouterOptions](#routeroptions) | Yes  | Description of the new page.|
W
wusongqing 已提交
84 85

**Example**
W
wusongqing 已提交
86

W
wusongqing 已提交
87
```js
W
wusongqing 已提交
88 89 90 91 92 93
router.replace({
  url: 'pages/detail',
  params: {
    data1: 'message',
  },
});
W
wusongqing 已提交
94
```
W
wusongqing 已提交
95

W
wusongqing 已提交
96 97 98 99 100 101 102 103 104
  ## router.replace<sup>9+</sup>

replace(options: RouterOptions, mode: RouterMode): void

Replaces the current page with another one in the application and destroys the current page.

**System capability**: SystemCapability.ArkUI.ArkUI.Full

**Parameters**
W
wusongqing 已提交
105 106 107 108
| Name    | Type                             | Mandatory  | Description        |
| ------- | ------------------------------- | ---- | ---------- |
| options | [RouterOptions](#routeroptions) | Yes   | Description of the new page. |
| mode    | [RouterMode](#routermode9)      | Yes   | Routing mode.|
W
wusongqing 已提交
109 110 111

**Example**

W
wusongqing 已提交
112
```js
W
wusongqing 已提交
113 114 115 116 117 118
router.replace({
  url: 'pages/detail/detail',
  params: {
    data1: 'message',
  },
}, router.RouterMode.Standard);
W
wusongqing 已提交
119
```
W
wusongqing 已提交
120 121 122 123 124 125 126 127 128 129

## router.back

back(options?: RouterOptions ): void

Returns to the previous page or a specified page.

**System capability**: SystemCapability.ArkUI.ArkUI.Full

**Parameters**
W
wusongqing 已提交
130 131
| Name | Type                           | Mandatory| Description                                                        |
| ------- | ------------------------------- | ---- | ------------------------------------------------------------ |
W
wusongqing 已提交
132
| options | [RouterOptions](#routeroptions) | No  | 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.|
W
wusongqing 已提交
133 134 135

**Example**

W
wusongqing 已提交
136 137 138
```js
router.back({url:'pages/detail'});    
```
W
wusongqing 已提交
139 140 141 142 143 144 145 146 147 148

## router.clear

clear(): void

Clears all historical pages in the stack and retains only the current page at the top of the stack.

**System capability**: SystemCapability.ArkUI.ArkUI.Full

**Example**
W
wusongqing 已提交
149

W
wusongqing 已提交
150
```js
W
wusongqing 已提交
151
router.clear();    
W
wusongqing 已提交
152
```
W
wusongqing 已提交
153 154 155 156 157 158 159

## router.getLength

getLength(): string

Obtains the number of pages in the current stack.

W
wusongqing 已提交
160 161
**System capability**: SystemCapability.ArkUI.ArkUI.Full

W
wusongqing 已提交
162
**Return value**
W
wusongqing 已提交
163 164
| Type    | Description                |
| ------ | ------------------ |
W
wusongqing 已提交
165
| string | Number of pages in the stack. The maximum value is **32**.|
W
wusongqing 已提交
166 167

**Example**
W
wusongqing 已提交
168
```js
W
wusongqing 已提交
169 170
var size = router.getLength();        
console.log('pages stack size = ' + size);    
W
wusongqing 已提交
171
```
W
wusongqing 已提交
172 173 174 175 176 177 178 179 180 181 182

## router.getState

getState(): RouterState

Obtains state information about the current page.

**System capability**: SystemCapability.ArkUI.ArkUI.Full

**Return value**

W
wusongqing 已提交
183 184
| Type                         | Description     |
| --------------------------- | ------- |
W
wusongqing 已提交
185
| [RouterState](#routerstate) | Page routing state.|
W
wusongqing 已提交
186 187 188 189 190 191 192 193 194
**Example**

```js
var page = router.getState();
console.log('current index = ' + page.index);
console.log('current name = ' + page.name);
console.log('current path = ' + page.path);
```

W
wusongqing 已提交
195
## RouterState
W
wusongqing 已提交
196

W
wusongqing 已提交
197 198 199 200
Describes the page routing state.

**System capability**: SystemCapability.ArkUI.ArkUI.Full

W
wusongqing 已提交
201 202
| Name   | Type    | Description                                |
| ----- | ------ | ---------------------------------- |
W
wusongqing 已提交
203
| index | number | Index of the current page in the stack. The index starts from 1 from the bottom to the top of the stack.|
W
wusongqing 已提交
204 205
| name  | string | Name of the current page, that is, the file name.                 |
| path  | string | Path of the current page.                        |
W
wusongqing 已提交
206 207 208 209 210 211 212 213 214 215

## router.enableAlertBeforeBackPage

enableAlertBeforeBackPage(options: EnableAlertOptions): void

Enables the display of a confirm dialog box before returning to the previous page.

**System capability**: SystemCapability.ArkUI.ArkUI.Full

**Parameters**
W
wusongqing 已提交
216 217 218
| Name    | Type                                      | Mandatory  | Description       |
| ------- | ---------------------------------------- | ---- | --------- |
| options | [EnableAlertOptions](#enablealertoptions) | Yes   | Description of the dialog box.|
W
wusongqing 已提交
219 220 221

**Example**

W
wusongqing 已提交
222 223 224 225
  ```js        
  router.enableAlertBeforeBackPage({            
    message: 'Message Info'        
  });    
W
wusongqing 已提交
226 227 228 229 230
  ```
## EnableAlertOptions

Describes the confirm dialog box.

W
wusongqing 已提交
231
**System capability**: SystemCapability.ArkUI.ArkUI.Full
W
wusongqing 已提交
232

W
wusongqing 已提交
233 234 235
| Name     | Type    | Mandatory  | Description      |
| ------- | ------ | ---- | -------- |
| message | string | Yes   | Content displayed in the confirm dialog box.|
W
wusongqing 已提交
236 237 238 239 240 241 242 243 244 245

## router.disableAlertBeforeBackPage

disableAlertBeforeBackPage(): void

Disables the display of a confirm dialog box before returning to the previous page.

**System capability**: SystemCapability.ArkUI.ArkUI.Full

**Example**
W
wusongqing 已提交
246
```js
W
wusongqing 已提交
247
router.disableAlertBeforeBackPage();    
W
wusongqing 已提交
248
```
W
wusongqing 已提交
249 250 251 252 253 254 255 256 257 258 259

##  router.getParams

getParams(): Object

Obtains the parameters passed from the page that initiates redirection to the current page.

**System capability**: SystemCapability.ArkUI.ArkUI.Full

**Return value**

W
wusongqing 已提交
260 261
| Type    | Description               |
| ------ | ----------------- |
W
wusongqing 已提交
262 263 264 265
| Object | Parameters passed from the page that initiates redirection to the current page.|

**Example**

W
wusongqing 已提交
266 267 268 269 270 271 272 273
```
router.getParams();
```

## RouterOptions

Describes the page routing options.

W
wusongqing 已提交
274
**System capability**: SystemCapability.ArkUI.ArkUI.Lite
W
wusongqing 已提交
275

W
wusongqing 已提交
276 277 278 279
| Name    | Type    | Mandatory  | Description                                      |
| ------ | ------ | ---- | ---------------------------------------- |
| url    | string | Yes   | URI of the destination page, in either of the following formats:<br>- Absolute path of the page. The value is available in the pages list in the **config.json** file, for example:<br>- pages/index/index<br>- pages/detail/detail<br>- Particular path. If the URI is a slash (/), the home page is displayed.|
| 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.|
W
wusongqing 已提交
280 281 282 283 284 285 286 287 288 289 290


  > **NOTE**
  > The page routing stack supports a maximum of 32 pages.

## RouterMode<sup>9+</sup>

Enumerates the routing modes.

**System capability**: SystemCapability.ArkUI.ArkUI.Full

W
wusongqing 已提交
291 292 293
| Name      | Description                                      |
| -------- | ---------------------------------------- |
| Standard | Standard mode.                                   |
W
wusongqing 已提交
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
| Single   | Singleton mode.<br>If the URL of the target page already exists in the page stack, the page closest to the top of the stack is moved as a new page to the top of the stack.<br>If the URL of the target page does not exist in the page stack, the page is redirected to in standard mode.|

## Examples

### JavaScript-based Web-like Development Paradigm

```js
// Current page
export default {
  pushPage() {
    router.push({
      url: 'pages/detail/detail',
      params: {
        data1: 'message',
      },
    });
W
wusongqing 已提交
310
  }
W
wusongqing 已提交
311 312 313 314 315 316
}
```
```js
// detail page
export default {
  onInit() {
W
wusongqing 已提交
317
    console.info('showData1:' + router.getParams()[data1]);
W
wusongqing 已提交
318
  }
W
wusongqing 已提交
319 320
}
```
W
wusongqing 已提交
321

W
wusongqing 已提交
322
### TypeScript-based Declarative Development Paradigm
W
wusongqing 已提交
323

W
wusongqing 已提交
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
```ts
// Navigate to the target page through router.push with the params parameter carried.
import router from '@ohos.router'

@Entry
@Component
struct Index {
  async  routePage() {
    let options = {
      url: 'pages/second',
      params: {
        text: 'This is the value on the first page.',
        data: {
          array: [12, 45, 78]
        },
W
wusongqing 已提交
339 340
      }
    }
W
wusongqing 已提交
341 342 343 344
    try {
      await router.push(options)
    } catch (err) {
      console.info(` fail callback, code: ${err.code}, msg: ${err.msg}`)
W
wusongqing 已提交
345 346 347
    }
  }

W
wusongqing 已提交
348 349 350
  build() {
    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
        Text('This is the first page.')
W
wusongqing 已提交
351 352
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
W
wusongqing 已提交
353 354 355 356 357 358 359 360 361 362
      Button() {
        Text('next page')
          .fontSize(25)
          .fontWeight(FontWeight.Bold)
      }.type(ButtonType.Capsule)
          .margin({ top: 20 })
          .backgroundColor('#ccc')
          .onClick(() => {
            this.routePage()
      })
W
wusongqing 已提交
363
    }
W
wusongqing 已提交
364 365
    .width('100%')
    .height('100%')
W
wusongqing 已提交
366
  }
W
wusongqing 已提交
367 368
}
```
W
wusongqing 已提交
369

W
wusongqing 已提交
370 371 372
```ts
// Receive the transferred parameters on the second page.
import router from '@ohos.router'
W
wusongqing 已提交
373

W
wusongqing 已提交
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
@Entry
@Component
struct Second {
  private content: string = "This is the second page."
  @State text: string = router.getParams()['text']
  @State data: any = router.getParams()['data']
  @State secondData : string = ''
  
  build() {
    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
      Text(`${this.content}`)
        .fontSize(50)
        .fontWeight(FontWeight.Bold)
      Text(this.text)
        .fontSize(30)
        .onClick(()=>{
          this.secondData = (this.data.array[1]).toString()
        })
      .margin({top:20})
      Text('Value from the first page '+'' + this.secondData)
        .fontSize(20)
        .margin({top:20})
        .backgroundColor('red')      
    }
    .width('100%')
    .height('100%')
  }
}
```