鸿蒙5.0开发进阶:ArkTS API UI界面-@ohos.router (页面路由)(不推荐)

往期鸿蒙全套实战文章必看:(文中附带全栈鸿蒙学习资料)


@ohos.router (页面路由)(不推荐)

本模块提供通过不同的url访问不同的页面,包括跳转到应用内的指定页面、同应用内的某个页面替换当前页面、返回上一页面或指定的页面等。

说明

  • 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。

  • 页面路由需要在页面渲染完成之后才能调用,在onInit和onReady生命周期中页面还处于渲染阶段,禁止调用页面路由方法。

  • 本模块功能依赖UI的执行上下文,不可在UI上下文不明确的地方使用,参见UIContext说明。

  • 从API version 10开始,可以通过使用UIContext中的getRouter方法获取当前UI上下文关联的Router对象。

  • 如果使用传入callback形式的pushUrlpushNamedRoute接口,callback中通过getLength等接口获取的栈信息为中间态的栈信息,可能与栈操作完全结束后,再通过getLength等接口获取的栈信息不一致。

导入模块

import { router } from '@kit.ArkUI';

router.pushUrl9+

pushUrl(options: RouterOptions): Promise<void>

跳转到应用内的指定页面。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

参数名类型必填说明
optionsRouterOptions跳转页面描述信息。

返回值:

类型说明
Promise<void>异常返回结果。

错误码:

以下错误码的详细介绍。

错误码ID错误信息
401Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.
100001Internal error.
100002Uri error. The URI of the page to redirect is incorrect or does not exist.
100003Page stack error. Too many pages are pushed.

示例:

import { BusinessError } from '@kit.BasicServicesKit';

class innerParams {
data3:number[]

constructor(tuple:number[]) {
this.data3 = tuple
}
}

class routerParams {
data1:string
data2:innerParams

constructor(str:string, tuple:number[]) {
this.data1 = str
this.data2 = new innerParams(tuple)
}
}

try {
router.pushUrl({
url: 'pages/routerpage2',
params: new routerParams('message' ,[123,456,789])
})
} catch (err) {
console.error(`pushUrl failed, code is ${(err as BusinessError).code}, message is ${(err as BusinessError).message}`);
}

router.pushUrl9+

pushUrl(options: RouterOptions, callback: AsyncCallback<void>): void

跳转到应用内的指定页面。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

参数名类型必填说明
optionsRouterOptions跳转页面描述信息。
callbackAsyncCallback<void>异常响应回调。

错误码:

以下错误码的详细介绍。

错误码ID错误信息
401Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.
100001Internal error.
100002Uri error. The URI of the page to redirect is incorrect or does not exist.
100003Page stack error. Too many pages are pushed.

示例:

class innerParams {
data3:number[]

constructor(tuple:number[]) {
this.data3 = tuple
}
}

class routerParams {
data1:string
data2:innerParams

constructor(str:string, tuple:number[]) {
this.data1 = str
this.data2 = new innerParams(tuple)
}
}

router.pushUrl({
url: 'pages/routerpage2',
params: new routerParams('message' ,[123,456,789])
}, (err) => {
if (err) {
console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`);
return;
}
console.info('pushUrl success');
})

router.pushUrl9+

pushUrl(options: RouterOptions, mode: RouterMode): Promise<void>

跳转到应用内的指定页面。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

参数名类型必填说明
optionsRouterOptions跳转页面描述信息。
modeRouterMode跳转页面使用的模式。

返回值:

类型说明
Promise<void>异常返回结果。

错误码:

以下错误码的详细介绍。

错误码ID错误信息
401Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.
100001Internal error.
100002Uri error. The URI of the page to redirect is incorrect or does not exist.
100003Page stack error. Too many pages are pushed.

示例:

import { BusinessError } from '@kit.BasicServicesKit';

class innerParams {
data3:number[]

constructor(tuple:number[]) {
this.data3 = tuple
}
}

class routerParams {
data1:string
data2:innerParams

constructor(str:string, tuple:number[]) {
this.data1 = str
this.data2 = new innerParams(tuple)
}
}

try {
router.pushUrl({
url: 'pages/routerpage2',
params: new routerParams('message' ,[123,456,789])
}, router.RouterMode.Standard)
} catch (err) {
console.error(`pushUrl failed, code is ${(err as BusinessError).code}, message is ${(err as BusinessError).message}`);
}

router.pushUrl9+

pushUrl(options: RouterOptions, mode: RouterMode, callback: AsyncCallback<void>): void

跳转到应用内的指定页面。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

参数名类型必填说明
optionsRouterOptions跳转页面描述信息。
modeRouterMode跳转页面使用的模式。
callbackAsyncCallback<void>异常响应回调。

错误码:

以下错误码的详细介绍。

错误码ID错误信息
401Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.
100001Internal error.
100002Uri error. The URI of the page to redirect is incorrect or does not exist.
100003Page stack error. Too many pages are pushed.

示例:

class innerParams {
data3:number[]

constructor(tuple:number[]) {
this.data3 = tuple
}
}

class routerParams {
data1:string
data2:innerParams

constructor(str:string, tuple:number[]) {
this.data1 = str
this.data2 = new innerParams(tuple)
}
}

router.pushUrl({
url: 'pages/routerpage2',
params: new routerParams('message' ,[123,456,789])
}, router.RouterMode.Standard, (err) => {
if (err) {
console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`);
return;
}
console.info('pushUrl success');
})

router.replaceUrl9+

replaceUrl(options: RouterOptions): Promise<void>

用应用内的某个页面替换当前页面,并销毁被替换的页面。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Lite

参数:

参数名类型必填说明
optionsRouterOptions替换页面描述信息。

返回值:

类型说明
Promise<void>异常返回结果。

错误码:

以下错误码的详细介绍。

错误码ID错误信息
401Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.
100001The UI execution context is not found. This error code is thrown only in the standard system.
200002Uri error. The URI of the page to be used for replacement is incorrect or does not exist.

示例:

import { BusinessError } from '@kit.BasicServicesKit';

class routerParams {
data1:string

constructor(str:string) {
this.data1 = str
}
}

try {
router.replaceUrl({
url: 'pages/detail',
params: new routerParams('message')
})
} catch (err) {
console.error(`replaceUrl failed, code is ${(err as BusinessError).code}, message is ${(err as BusinessError).message}`);
}

router.replaceUrl9+

replaceUrl(options: RouterOptions, callback: AsyncCallback<void>): void

用应用内的某个页面替换当前页面,并销毁被替换的页面。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Lite

参数:

参数名类型必填说明
optionsRouterOptions替换页面描述信息。
callbackAsyncCallback<void>异常响应回调。

错误码:

以下错误码的详细介绍。

错误码ID错误信息
401Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.
100001The UI execution context is not found. This error code is thrown only in the standard system.
200002Uri error. The URI of the page to be used for replacement is incorrect or does not exist.

示例:

class routerParams {
data1:string

constructor(str:string) {
this.data1 = str
}
}

router.replaceUrl({
url: 'pages/detail',
params: new routerParams('message')
}, (err) => {
if (err) {
console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`);
return;
}
console.info('replaceUrl success');
})

router.replaceUrl9+

replaceUrl(options: RouterOptions, mode: RouterMode): Promise<void>

用应用内的某个页面替换当前页面,并销毁被替换的页面。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Lite

参数:

参数名类型必填说明
optionsRouterOptions替换页面描述信息。
modeRouterMode跳转页面使用的模式。

返回值:

类型说明
Promise<void>异常返回结果。

错误码:

以下错误码的详细介绍。

错误码ID错误信息
401Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.
100001Failed to get the delegate. This error code is thrown only in the standard system.
200002Uri error. The URI of the page to be used for replacement is incorrect or does not exist.

示例:

import { BusinessError } from '@kit.BasicServicesKit';

class routerParams {
data1:string

constructor(str:string) {
this.data1 = str
}
}

try {
router.replaceUrl({
url: 'pages/detail',
params: new routerParams('message')
}, router.RouterMode.Standard)
} catch (err) {
console.error(`replaceUrl failed, code is ${(err as BusinessError).code}, message is ${(err as BusinessError).message}`);
}

router.replaceUrl9+

replaceUrl(options: RouterOptions, mode: RouterMode, callback: AsyncCallback<void>): void

用应用内的某个页面替换当前页面,并销毁被替换的页面。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Lite

参数:

参数名类型必填说明
optionsRouterOptions替换页面描述信息。
modeRouterMode跳转页面使用的模式。
callbackAsyncCallback<void>异常响应回调。

错误码:

以下错误码的详细介绍。

错误码ID错误信息
401Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.
100001The UI execution context is not found. This error code is thrown only in the standard system.
200002Uri error. The URI of the page to be used for replacement is incorrect or does not exist.

示例:

class routerParams {
data1:string

constructor(str:string) {
this.data1 = str
}
}

router.replaceUrl({
url: 'pages/detail',
params: new routerParams('message')
}, router.RouterMode.Standard, (err) => {
if (err) {
console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`);
return;
}
console.info('replaceUrl success');
});

router.pushNamedRoute10+

pushNamedRoute(options: NamedRouterOptions): Promise<void>

跳转到指定的命名路由页面。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

参数名类型必填说明
optionsNamedRouterOptions跳转页面描述信息。

返回值:

类型说明
Promise<void>异常返回结果。

错误码:

以下错误码的详细介绍。

错误码ID错误信息
401Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.
100001Internal error.
100003Page stack error. Too many pages are pushed.
100004Named route error. The named route does not exist.

示例:

import { BusinessError } from '@kit.BasicServicesKit';
class innerParams {
data3:number[]
constructor(tuple:number[]) {
this.data3 = tuple
}
}
class routerParams {
data1:string
data2:innerParams
constructor(str:string, tuple:number[]) {
this.data1 = str
this.data2 = new innerParams(tuple)
}
}
try {
router.pushNamedRoute({
name: 'myPage',
params: new routerParams('message' ,[123,456,789])
})
} catch (err) {
console.error(`pushNamedRoute failed, code is ${(err as BusinessError).code}, message is ${(err as BusinessError).message}`);
}

​

router.pushNamedRoute10+

pushNamedRoute(options: NamedRouterOptions, callback: AsyncCallback<void>): void

跳转到指定的命名路由页面。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

参数名类型必填说明
optionsNamedRouterOptions跳转页面描述信息。
callbackAsyncCallback<void>异常响应回调。

错误码:

以下错误码的详细介绍。

错误码ID错误信息
401Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.
100001Internal error.
100003Page stack error. Too many pages are pushed.
100004Named route error. The named route does not exist.

示例:

class innerParams {
data3:number[]

constructor(tuple:number[]) {
this.data3 = tuple
}
}

class routerParams {
data1:string
data2:innerParams

constructor(str:string, tuple:number[]) {
this.data1 = str
this.data2 = new innerParams(tuple)
}
}

router.pushNamedRoute({
name: 'myPage',
params: new routerParams('message' ,[123,456,789])
}, (err) => {
if (err) {
console.error(`pushNamedRoute failed, code is ${err.code}, message is ${err.message}`);
return;
}
console.info('pushNamedRoute success');
})

router.pushNamedRoute10+

pushNamedRoute(options: NamedRouterOptions, mode: RouterMode): Promise<void>

跳转到指定的命名路由页面。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

参数名类型必填说明
optionsNamedRouterOptions跳转页面描述信息。
modeRouterMode跳转页面使用的模式。

返回值:

类型说明
Promise<void>异常返回结果。

错误码:

以下错误码的详细介绍。

错误码ID错误信息
401Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.
100001Internal error.
100003Page stack error. Too many pages are pushed.
100004Named route error. The named route does not exist.

示例:

import { BusinessError } from '@kit.BasicServicesKit';

class innerParams {
data3:number[]

constructor(tuple:number[]) {
this.data3 = tuple
}
}

class routerParams {
data1:string
data2:innerParams

constructor(str:string, tuple:number[]) {
this.data1 = str
this.data2 = new innerParams(tuple)
}
}

try {
router.pushNamedRoute({
name: 'myPage',
params: new routerParams('message' ,[123,456,789])
}, router.RouterMode.Standard)
} catch (err) {
console.error(`pushNamedRoute failed, code is ${(err as BusinessError).code}, message is ${(err as BusinessError).message}`);
}

router.pushNamedRoute10+

pushNamedRoute(options: NamedRouterOptions, mode: RouterMode, callback: AsyncCallback<void>): void

跳转到指定的命名路由页面。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

参数名类型必填说明
optionsNamedRouterOptions跳转页面描述信息。
modeRouterMode跳转页面使用的模式。
callbackAsyncCallback<void>异常响应回调。

错误码:

以下错误码的详细介绍。

错误码ID错误信息
401Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.
100001Internal error.
100003Page stack error. Too many pages are pushed.
100004Named route error. The named route does not exist.

示例:

class innerParams {
data3:number[]

constructor(tuple:number[]) {
this.data3 = tuple
}
}

class routerParams {
data1:string
data2:innerParams

constructor(str:string, tuple:number[]) {
this.data1 = str
this.data2 = new innerParams(tuple)
}
}

router.pushNamedRoute({
name: 'myPage',
params: new routerParams('message' ,[123,456,789])
}, router.RouterMode.Standard, (err) => {
if (err) {
console.error(`pushNamedRoute failed, code is ${err.code}, message is ${err.message}`);
return;
}
console.info('pushNamedRoute success');
})

router.replaceNamedRoute10+

replaceNamedRoute(options: NamedRouterOptions): Promise<void>

用指定的命名路由页面替换当前页面,并销毁被替换的页面。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

参数名类型必填说明
optionsNamedRouterOptions替换页面描述信息。

返回值:

类型说明
Promise<void>异常返回结果。

错误码:

以下错误码的详细介绍。

错误码ID错误信息
401Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.
100001The UI execution context is not found. This error code is thrown only in the standard system.
100004Named route error. The named route does not exist.

示例:

import { BusinessError } from '@kit.BasicServicesKit';

class routerParams {
data1:string

constructor(str:string) {
this.data1 = str
}
}

try {
router.replaceNamedRoute({
name: 'myPage',
params: new routerParams('message')
})
} catch (err) {
console.error(`replaceNamedRoute failed, code is ${(err as BusinessError).code}, message is ${(err as BusinessError).message}`);
}

router.replaceNamedRoute10+

replaceNamedRoute(options: NamedRouterOptions, callback: AsyncCallback<void>): void

用指定的命名路由页面替换当前页面,并销毁被替换的页面。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

参数名类型必填说明
optionsNamedRouterOptions替换页面描述信息。
callbackAsyncCallback<void>异常响应回调。

错误码:

以下错误码的详细介绍。

错误码ID错误信息
401Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.
100001The UI execution context is not found. This error code is thrown only in the standard system.
100004Named route error. The named route does not exist.

示例:

class routerParams {
data1:string

constructor(str:string) {
this.data1 = str
}
}

router.replaceNamedRoute({
name: 'myPage',
params: new routerParams('message')
}, (err) => {
if (err) {
console.error(`replaceNamedRoute failed, code is ${err.code}, message is ${err.message}`);
return;
}
console.info('replaceNamedRoute success');
})

router.replaceNamedRoute10+

replaceNamedRoute(options: NamedRouterOptions, mode: RouterMode): Promise<void>

用指定的命名路由页面替换当前页面,并销毁被替换的页面。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

参数名类型必填说明
optionsNamedRouterOptions替换页面描述信息。
modeRouterMode跳转页面使用的模式。

返回值:

类型说明
Promise<void>异常返回结果。

错误码:

以下错误码的详细介绍。

错误码ID错误信息
401Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.
100001Failed to get the delegate. This error code is thrown only in the standard system.
100004Named route error. The named route does not exist.

示例:

import { BusinessError } from '@kit.BasicServicesKit';

class routerParams {
data1:string

constructor(str:string) {
this.data1 = str
}
}

try {
router.replaceNamedRoute({
name: 'myPage',
params: new routerParams('message')
}, router.RouterMode.Standard)
} catch (err) {
console.error(`replaceNamedRoute failed, code is ${(err as BusinessError).code}, message is ${(err as BusinessError).message}`);
}

router.replaceNamedRoute10+

replaceNamedRoute(options: NamedRouterOptions, mode: RouterMode, callback: AsyncCallback<void>): void

用指定的命名路由页面替换当前页面,并销毁被替换的页面。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

参数名类型必填说明
optionsNamedRouterOptions替换页面描述信息。
modeRouterMode跳转页面使用的模式。
callbackAsyncCallback<void>异常响应回调。

错误码:

以下错误码的详细介绍。

错误码ID错误信息
401Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.
100001The UI execution context is not found. This error code is thrown only in the standard system.
100004Named route error. The named route does not exist.

示例:

class routerParams {
data1:string

constructor(str:string) {
this.data1 = str
}
}

router.replaceNamedRoute({
name: 'myPage',
params: new routerParams('message')
}, router.RouterMode.Standard, (err) => {
if (err) {
console.error(`replaceNamedRoute failed, code is ${err.code}, message is ${err.message}`);
return;
}
console.info('replaceNamedRoute success');
});

router.back

back(options?: RouterOptions ): void

返回上一页面或指定的页面,会删除当前页面与指定页面之间的所有页面。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

参数名类型必填说明
optionsRouterOptions返回页面描述信息,其中参数url指路由跳转时会返回到指定url的界面,如果页面栈上没有url页面,则不响应该情况。如果url未设置,则返回上一页,页面不会重新构建,页面栈里面的page不会回收,出栈后会被回收。back是返回接口,url设置为特殊值"/"不生效。

示例:

router.back({url:'pages/detail'});

router.back12+

back(index: number, params?: Object): void;

返回指定的页面,会删除当前页面与指定页面之间的所有页面。

元服务API: 从API version 12开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

参数名类型必填说明
indexnumber跳转目标页面的索引值。
paramsObject页面返回时携带的参数。

示例:

router.back(1);
router.back(1, {info: '来自Home页'}); //携带参数返回

router.clear

clear(): void

清空页面栈中的所有历史页面,仅保留当前页面作为栈顶页面。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

示例:

router.clear();

router.getLength

getLength(): string

获取当前在页面栈内的页面数量。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

返回值:

类型说明
string页面数量,页面栈支持最大数值是32。

示例:

let size = router.getLength();
console.log('pages stack size = ' + size);

router.getState

getState(): RouterState

获取栈顶页面的状态信息。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

返回值:

类型说明
RouterState页面状态信息。

示例:

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

router.getStateByIndex12+

getStateByIndex(index: number): RouterState | undefined

通过索引值获取对应页面的状态信息。

元服务API: 从API version 12开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

参数名类型必填说明
indexnumber表示要获取的页面索引。

返回值:

类型说明
RouterState | undefined返回页面状态信息。索引不存在时返回undefined。

示例:

let options:router.RouterState | undefined = router.getStateByIndex(1);
if (options != undefined) {
console.log('index = ' + options.index);
console.log('name = ' + options.name);
console.log('path = ' + options.path);
console.log('params = ' + options.params);
}

router.getStateByUrl12+

getStateByUrl(url: string): Array<RouterState>

通过url获取对应页面的状态信息。

元服务API: 从API version 12开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

参数名类型必填说明
urlstring表示要获取对应页面信息的url。

返回值:

类型说明
Array<RouterState>页面状态信息。

示例:

let options:Array<router.RouterState> = router.getStateByUrl('pages/index');
for (let i: number = 0; i < options.length; i++) {
console.log('index = ' + options[i].index);
console.log('name = ' + options[i].name);
console.log('path = ' + options[i].path);
console.log('params = ' + options[i].params);
}

RouterState

页面状态信息。

系统能力: SystemCapability.ArkUI.ArkUI.Full。

名称类型必填说明
indexnumber

表示当前页面在页面栈中的索引。从栈底到栈顶,index从1开始递增。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

namestring

表示当前页面的名称,即对应文件名。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

pathstring

表示当前页面的路径。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

params12+Object

表示当前页面携带的参数。

元服务API: 从API version 12开始,该接口支持在元服务中使用。

router.showAlertBeforeBackPage9+

showAlertBeforeBackPage(options: EnableAlertOptions): void

开启页面返回询问对话框。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

参数名类型必填说明
optionsEnableAlertOptions文本弹窗信息描述。

错误码:

以下错误码的详细介绍。

错误码ID错误信息
401Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.
100001Internal error.

示例:

import { BusinessError } from '@kit.BasicServicesKit';

try {
router.showAlertBeforeBackPage({
message: 'Message Info'
});
} catch(err) {
console.error(`showAlertBeforeBackPage failed, code is ${(err as BusinessError).code}, message is ${(err as BusinessError).message}`);
}

EnableAlertOptions

页面返回询问对话框选项。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: 以下各项对应的系统能力均为SystemCapability.ArkUI.ArkUI.Full。

名称类型必填说明
messagestring询问对话框内容。

router.hideAlertBeforeBackPage9+

hideAlertBeforeBackPage(): void

禁用页面返回询问对话框。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

示例:

router.hideAlertBeforeBackPage();

router.getParams

getParams(): Object

获取发起跳转的页面往当前页传入的参数。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

返回值:

类型说明
object发起跳转的页面往当前页传入的参数。

示例:

router.getParams();

RouterOptions

路由跳转选项。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Lite。

名称类型必填说明
urlstring

表示目标页面的url,可以用以下两种格式:

- 页面绝对路径,由配置文件中pages列表提供,例如:

- pages/index/index

- pages/detail/detail

- 特殊值,如果url的值是"/",则跳转到首页,首页默认为页面跳转配置项src数组的第一个数据项。

paramsObject

表示路由跳转时要同时传递到目标页面的数据,切换到其他页面时,当前接收的数据失效。跳转到目标页面后,使用router.getParams()获取传递的参数,此外,在类web范式中,参数也可以在页面中直接使用,如this.keyValue(keyValue为跳转时params参数中的key值),如果目标页面中已有该字段,则其值会被传入的字段值覆盖。

说明:

params参数不能传递方法和系统接口返回的对象(例如,媒体接口定义和返回的PixelMap对象)。建议开发者提取系统接口返回的对象中需要被传递的基础类型属性,自行构造object类型对象进行传递。

说明

页面路由栈支持的最大Page数量为32。

RouterMode9+

路由跳转模式。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full。

名称说明
Standard

多实例模式,也是默认情况下的跳转模式。

目标页面会被添加到页面栈顶,无论栈中是否存在相同url的页面。

说明:

不使用路由跳转模式时,则按照默认的多实例模式进行跳转。

Single

单实例模式。

如果目标页面的url已经存在于页面栈中,则该url页面移动到栈顶。

如果目标页面的url在页面栈中不存在同url页面,则按照默认的多实例模式进行跳转。

NamedRouterOptions10+

命名路由跳转选项。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

名称类型必填说明
namestring表示目标命名路由页面的name。
paramsObject

表示路由跳转时要同时传递到目标页面的数据。跳转到目标页面后,使用router.getParams()获取传递的参数,此外,在类web范式中,参数也可以在页面中直接使用,如this.keyValue(keyValue为跳转时params参数中的key值),如果目标页面中已有该字段,则其值会被传入的字段值覆盖。

说明:

params参数不能传递方法和系统接口返回的对象(例如,媒体接口定义和返回的PixelMap对象)。建议开发者提取系统接口返回的对象中需要被传递的基础类型属性,自行构造object类型对象进行传递。

完整示例

基于JS扩展的类Web开发范式

以下代码仅适用于javascript文件,不适用于ArkTS文件

// 在当前页面中
export default {
pushPage() {
router.pushUrl({
url: 'pages/detail/detail',
params: {
data1: 'message'
}
});
}
}
// 在detail页面中
export default {
onInit() {
console.info('showData1:' + router.getParams()['data1']);
}
}

基于TS扩展的声明式开发范式

说明

直接使用router可能导致实例不明确的问题,建议使用getUIContext获取UIContext实例,并使用getRouter获取绑定实例的router。

// 通过router.pushUrl跳转至目标页携带params参数
import { router } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit'

// 定义传递参数的类
class innerParams {
array:number[]

constructor(tuple:number[]) {
this.array = tuple
}
}

class routerParams {
text:string
data:innerParams

constructor(str:string, tuple:number[]) {
this.text = str
this.data = new innerParams(tuple)
}
}

@Entry
@Component
struct Index {
async routePage() {
let options:router.RouterOptions = {
url: 'pages/second',
params: new routerParams('这是第一页的值' ,[12, 45, 78])
}
try {
// 建议使用this.getUIContext().getRouter().pushUrl()
await router.pushUrl(options)
} catch (err) {
console.info(` fail callback, code: ${(err as BusinessError).code}, msg: ${(err as BusinessError).message}`)
}
}

build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Text('这是第一页')
.fontSize(50)
.fontWeight(FontWeight.Bold)
Button() {
Text('next page')
.fontSize(25)
.fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule)
.margin({ top: 20 })
.backgroundColor('#ccc')
.onClick(() => {
this.routePage()
})
}
.width('100%')
.height('100%')
}
}
// 在second页面中接收传递过来的参数
import { router } from '@kit.ArkUI';

class innerParams {
array:number[]

constructor(tuple:number[]) {
this.array = tuple
}
}

class routerParams {
text:string
data:innerParams

constructor(str:string, tuple:number[]) {
this.text = str
this.data = new innerParams(tuple)
}
}

@Entry
@Component
struct Second {
private content: string = "这是第二页"
// 建议使用this.getUIContext().getRouter().getParams()
@State text: string = (router.getParams() as routerParams).text
@State data: object = (router.getParams() as routerParams).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(`第一页传来的数值:${this.secondData}`)
.fontSize(20)
.margin({ top: 20 })
.backgroundColor('red')
}
.width('100%')
.height('100%')
}
}

router.push(deprecated)

push(options: RouterOptions): void

跳转到应用内的指定页面。

从API version9开始不再维护,建议使用pushUrl9+

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

参数名类型必填说明
optionsRouterOptions跳转页面描述信息。

示例:

class innerParams {
data3:number[]

constructor(tuple:number[]) {
this.data3 = tuple
}
}

class routerParams {
data1:string
data2:innerParams

constructor(str:string, tuple:number[]) {
this.data1 = str
this.data2 = new innerParams(tuple)
}
}

router.push({
url: 'pages/routerpage2',
params: new routerParams('message' ,[123,456,789])
});

router.replace(deprecated)

replace(options: RouterOptions): void

用应用内的某个页面替换当前页面,并销毁被替换的页面。

从API version9开始不再维护,建议使用replaceUrl9+

系统能力: SystemCapability.ArkUI.ArkUI.Lite

参数:

参数名类型必填说明
optionsRouterOptions替换页面描述信息。

示例:

class routerParams {
data1:string

constructor(str:string) {
this.data1 = str
}
}

router.replace({
url: 'pages/detail',
params: new routerParams('message')
});

router.enableAlertBeforeBackPage(deprecated)

enableAlertBeforeBackPage(options: EnableAlertOptions): void

开启页面返回询问对话框。

从API version9开始不再维护,建议使用showAlertBeforeBackPage9+

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

参数名类型必填说明
optionsEnableAlertOptions文本弹窗信息描述。

示例:

router.enableAlertBeforeBackPage({
message: 'Message Info'
});

router.disableAlertBeforeBackPage(deprecated)

disableAlertBeforeBackPage(): void

禁用页面返回询问对话框。

从API version9开始不再维护,建议使用hideAlertBeforeBackPage9+

系统能力: SystemCapability.ArkUI.ArkUI.Full

示例:

router.disableAlertBeforeBackPage();

鸿蒙ui界面1.创建至少5个有关联的page 2.实现页面之间的路由跳转功能 3.部分页面加入统一的导航栏风格 4.使用ArkTS/ArkUI进行界面开发 5.使用Arkts实现业务逻辑 技术要求 1.使用鸿蒙5.0最新API开发工具 2.页面布局使用ArkUI声明式语法 3.状态管理使用@State、@Prop、@Link等装饰器 4.路由跳转使用@ohos.router模块 5.尝试使用数据持久化@ohos.data.preferences 页面具体要求 1. 首页 (IndexPage) 使用@Entry装饰器设置为应用入口 包含应用简介和主要功能入口按钮 实现Swiper轮播组件(至少3张图片自动轮播) 包含导航到其他页面路由按钮 最后可以适配同屏幕尺寸(响应式布局) IndexPage页面效果 核心代码 2. 注册页面 (RegisterPage) 使用Column、Row或 Flex等布局构建表单 尽量包含以下表单字段: 用户名(TextInput,必填,4-16字符) 密码(TextInput,type为Password,6-20字符) 确认密码(需与密码一致验证) 电子邮箱(格式验证) 手机号码(可选,格式验证) 性别(Radio组件) 兴趣爱好(Checkbox组) 表单提交前进行前端验证 使用@State管理表单状态 注册成功跳转到登录页面 RegisterPage页面效果 核心代码 3. 登录页面 (LoginPage) 包含登录表单: 用户名/邮箱输入框 密码输入框 "记住我"Toggle组件 忘记密码文本按钮 实现简单的登录状态管理 登录成功跳转到用户主页 提供注册页面路由链接 LoginPage页面效果 核心代码 4. 列表页面 (ListPage) 使用List组件展示数据 添加模拟数据至少20条 支持按某字段排序(如使用Picker组件选择排序方式) 点击列表项使用router.push跳转到详情页 包含Search组件实现搜索过滤 ListPage页面效果 核心代码 5. 详情页面 (DetailPage) 展示列表项选中项目的详细信息 使用router.getParams获取传递的参数 包含返回按钮(router.back) 图片展示使用Image组件 可选的收藏功能(使用本地存储)
最新发布
04-28
### 鸿蒙5.0使用ArkTSArkUI开发页面应用 以下是基于鸿蒙5.0 APIArkTSArkUI 开发一个多页面应用的核心实现方法,涵盖了页面创建、路由跳转、导航栏风格、状态管理、Swiper 轮播组件、表单验证、列表展示及详情页功能以及数据持久化的代码示例。 --- #### 1. 页面创建与路由跳转 通过 `Router` 实现页面间的跳转。以下是一个简单的 Page 定义及其跳转逻辑: ```typescript // MainPage.ets (主页) @Entry @Component struct MainPage { build() { Router.push({ uri: 'pages/SecondPage', params: { key: 'value' } }) Column() { Text('Main Page') .fontSize(20) .fontWeight(FontWeight.Bold) }.width('100%').height('100%') } } // SecondPage.ets (第二个页面) @Component struct SecondPage { @Param paramKey: string; build() { Column() { Text(`Second Page - Param: ${this.paramKey}`) .fontSize(20) .fontWeight(FontWeight.Bold) Button('Go Back') { Router.back() } }.width('100%').height('100%') } } ``` 以上代码展示了两个页面之间的跳转方式,并传递了一个参数给目标页面[^4]。 --- #### 2. 统一的导航栏风格 可以通过自定义组件来实现统一的导航栏样式: ```typescript // NavigationBar.ts @Component struct NavigationBar { title: string; build() { Row({ justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) { Text(this.title).fontColor(Color.White).fontSize(20).fontWeight(FontWeight.Bold) } .backgroundColor(Color.Blue) .height(60) } } // MainPage.ets 中调用 build() { Column() { NavigationBar(title: 'Home') Text('Main Page Content') .margin({ top: 20 }) .fontSize(18) } .width('100%') .height('100%') } ``` 此部分实现了带有标题的固定导航栏设计[^5]。 --- #### 3. 状态管理 (@State 和 @Prop) 利用 `@State` 进行本地状态管理和 `@Prop` 接收父级传入的数据: ```typescript // StateManagementExample.ets @Component struct CounterComponent { @State count: number = 0; increment() { this.count++; } decrement() { if (this.count > 0) { this.count--; } } build() { Column() { Text(`Count: ${this.count}`).fontSize(20) Row() { Button('+') { this.increment(); }.padding(10) Button('-') { this.decrement(); }.padding(10) } } .width('100%') .height('100%') } } ``` 在此例子中,`@State` 变量被用来存储计数器的状态,并提供了修改它的函数[^6]。 --- #### 4. Swiper 轮播组件 使用内置的 `Swiper` 组件可以轻松实现图片轮播效果: ```typescript // SwiperExample.ets @Component struct SwiperExample { images: Array<string> = [ 'https://example.com/image1.jpg', 'https://example.com/image2.jpg', 'https://example.com/image3.jpg' ]; build() { Swiper({ autoplay: true, interval: 3000 }) { ForEach(this.images, (image, index) => ( Image(image) .objectFit(ImageObjectFit.Cover) .width('100%') .height(200) )) } } } ``` 这段代码演示了如何配置自动播放和间隔时间的轮播图[^7]。 --- #### 5. 表单验证 通过监听输入框的变化事件来进行实时校验: ```typescript // FormValidation.ets @Component struct LoginForm { @State username: string = ''; @State password: string = ''; validateForm(): boolean { return this.username.length >= 5 && this.password.length >= 6; } submitForm() { if (!this.validateForm()) { console.error('Invalid form data'); return; } // Submit logic here... } build() { Column() { TextField('', value => this.username = value) .placeholder('Username (min 5 chars)') .onChange(() => this.validateForm()) TextField('', value => this.password = value, { type: InputType.Password }) .placeholder('Password (min 6 chars)') .onChange(() => this.validateForm()) Button('Login', () => this.submitForm()) .disabled(!this.validateForm()) } .width('100%') .height('100%') } } ``` 这里提供了一种基本的用户名和密码字段验证机制[^8]。 --- #### 6. 列表展示及详情页 借助 `List` 和 `ListItem` 构建可点击项链接到详情页的功能: ```typescript // ListViewAndDetail.ets @Component struct ProductListView { products: Array<{ id: number; name: string }> = [ { id: 1, name: 'Product A' }, { id: 2, name: 'Product B' }, { id: 3, name: 'Product C' } ]; navigateToDetail(id: number) { Router.push({ uri: 'pages/ProductDetail', params: { productId: String(id) } }); } build() { List() { ForEach(this.products, product => ( ListItem().onClick(() => this.navigateToDetail(product.id)) { Text(`${product.name} (#${product.id})`).fontSize(18) } )) } } } // ProductDetail.ets @Component struct ProductDetail { @Param productId: string; build() { Column() { Text(`Details of Product ID: ${this.productId}`).fontSize(20) } .width('100%') .height('100%') } } ``` 该片段描述了从产品列表进入特定产品的详细视图的过程[^9]。 --- #### 7. 数据持久化 (`@ohos.data.preferences`) 保存用户偏好设置或其他轻量级数据至设备存储中: ```typescript import preferences from '@ohos.data.preferences'; async function saveData(key: string, value: any): Promise<void> { const pref = await preferences.createPreferences('my_prefs'); await pref.put(key, JSON.stringify(value)); } async function getData(key: string): Promise<any> { const pref = await preferences.createPreferences('my_prefs'); const result = await pref.get(key); return result ? JSON.parse(result) : null; } // Example Usage saveData('username', 'JohnDoe'); // Save a user's name. const savedName = await getData('username'); // Retrieve the stored name. console.log(savedName); // Output: JohnDoe ``` 上述代码片段显示了如何使用 Preferences API 来存取键值对形式的小型数据集[^10]。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值