#Harmony篇:Navigation导航
Navigation导航跳转
包括单栏(Stack)、分栏(Split)和自适应(Auto)三种显示模式
@ComponentV2
export struct Dashboard {// 定义@Local pagesInfos: NavPathStack = new NavPathStack()@BuilderpageMap(name: string) {if (name == 'page1') {pageOne()} else if (name == 'page2') {pageTow()}}build() {Navigation(this.pagesInfos) { // 注入Button('Page1').onClick((event: ClickEvent) => {// 跳转this.pagesInfos.pushPath({name: 'page1'})})Button('Page2').onClick((event: ClickEvent) => {// 跳转this.pagesInfos.pushPath({name: 'page2'})})}.navDestination(this.pageMap) // 绑定.mode(NavigationMode.Stack) // 模式}
}// 跳转的页面1
@ComponentV2
struct pageOne {build() {NavDestination() {Text('page1-show')}}
}// 跳转的页面2
@ComponentV2
struct pageTow {build() {NavDestination() {Text('page2-show')}}
}
跳转
- pushPath
- pushPathByName
- pushDestination
- pushDestinationByName
// 普通跳转
this.pageStack.pushPath({name: 'PageOne',param: 'PageOne Param'})this.pageStack.pushPathByName('PageOne','PageOne Param')// 带返回回调的跳转
this.pageStack.pushPathByName('PageOne','PageOne Param',(popInfo) => {console.info('Pop page name is:' + popInfo.info.name)
})
返回
// 返回到上一页
this.pageStack.pop();
// 返回到上一个PageOne页面
this.pageStack.popToName("PageOne");
// 返回到索引为1的页面
this.pageStack.popToIndex(1);
// 返回到根首页(清除栈中所有页面)
this.pageStack.clear();
页面替换
// 将栈顶页面替换为PageOne
this.pageStack.replacePath({ name: "PageOne", param: "PageOne Param" });
this.pageStack.replacePathByName("PageOne", "PageOne Param");
// 带错误码的替换,跳转结束会触发异步回调,返回错误码信息
this.pageStack.replaceDestination({name: "PageOne", param: "PageOne Param"}).catch((error: BusinessError) => {console.error(`Replace destination failed, error code = ${error.code}, error.message = ${error.message}.`);}).then(() => {console.info('Replace destination succeed.');})
页面删除
// 删除栈中name为PageOne的所有页面
this.pageStack.removeByName("PageOne");
// 删除指定索引的页面
this.pageStack.removeByIndexes([1, 3, 5]);
// 删除指定id的页面
this.pageStack.removeByNavDestinationId("1");
生命周期
aboutToAppear:在创建自定义组件后,执行其build()函数之前执行(NavDestination创建之前),允许在该方法中改变状态变量,更改将在后续执行build()函数中生效。
onWillAppear:NavDestination创建后,挂载到组件树之前执行,在该方法中更改状态变量会在当前帧显示生效。
onAppear:通用生命周期事件,NavDestination组件挂载到组件树时执行。
onWillShow:NavDestination组件布局显示之前执行,此时页面不可见(应用切换到前台不会触发)。
onShown:NavDestination组件布局显示之后执行,此时页面已完成布局。
onActive:NavDestination处于激活态(处于栈顶可操作,且上层无特殊组件遮挡)触发。
onWillHide:NavDestination组件触发隐藏之前执行(应用切换到后台不会触发)。
onInactive:NavDestination组件处于非激活态(处于非栈顶不可操作,或处于栈顶时上层有特殊组件遮挡)触发。
onHidden:NavDestination组件触发隐藏后执行(非栈顶页面push进栈,栈顶页面pop出栈或应用切换到后台)。
onWillDisappear:NavDestination组件即将销毁之前执行,如果有转场动画,会在动画前触发(栈顶页面pop出栈)。
onDisappear:通用生命周期事件,NavDestination组件从组件树上卸载销毁时执行。
aboutToDisappear:自定义组件析构销毁之前执行,不允许在该方法中改变状态变量。
在这里插入代码片
