简介
Navigation是路由容器组件,包括单栏(Stack)、分栏(Split)和自适应(Auto)三种显示模式。适用于模块内和跨模块的路由切换。
 在页面跳转时,应该使用页面路由router,在页面内的页面跳转时,建议使用Navigation达到更好的转场动效场景。
UI框架

显示模式
通过mode属性来定义
Navigation() {
  ...
}
.mode(NavigationMode.Auto)
自适应(Auto)模式
组件默认的模式,当页面宽度大于等于一定阈值( API version 9及以前:520vp,API version 10及以后:600vp )时,Navigation组件采用分栏模式,反之采用单栏模式。
单栏(Stack)模式

分栏(Split)模式

标题栏模式
通过titleMode属性设置标题栏模式,分别有Mini模式和Full模式
- Mini模式
  
- Full模式
  
菜单栏
通过menus属性进行设置。支持Array和CustomBuilder两种类型。
 注意:使用Array时,竖屏最多支持3个图标,横屏最多支持5个图标
@Entry
@Component
struct Index {
  ToolTmp: NavigationMenuItem = {
    value: "",
    icon: "resources/base/media/startIcon.png",
    action: () => {
    }
  }
  build() {
    Column() {
      Navigation() {
      }
      .title("主标题")
      .titleMode(NavigationTitleMode.Full)
      .menus([
        this.ToolTmp,
        this.ToolTmp,
        this.ToolTmp
      ])
    }
    .width("100%")
    .height("100%")
    .backgroundColor('#F1F3F5')
  }
}
工具栏
工具栏位于Navigation组件的底部,通过toolbarConfiguration属性进行设置。
@Entry
@Component
struct Index {
  ToolTmp: NavigationMenuItem = {
    value: "",
    icon: "resources/base/media/startIcon.png",
    action: () => {
    }
  }
  Toolbar: ToolbarItem = {
    value: "test",
    icon: $r('app.media.app_icon'),
    action: () => {
    }
  }
  build() {
    Column() {
      Navigation() {
      }
      .title("主标题")
      .titleMode(NavigationTitleMode.Full)
      .menus([
        this.ToolTmp,
        this.ToolTmp,
        this.ToolTmp
      ])
      .toolbarConfiguration([
        this.Toolbar,
        this.Toolbar,
        this.Toolbar
      ])
    }
    .width("100%")
    .height("100%")
    .backgroundColor('#F1F3F5')
  }
}
路由操作
Navigation路由相关的操作都是基于页面栈NavPathStack对象。主要涉及页面跳转、页面返回、页面替换、页面删除、参数获取、路由拦截等功能。
 定义一个NavPathStack对象:pageStack: NavPathStack = new NavPathStack()
 
页面跳转
- 普通跳转,通过页面的name去跳转
this.pageStack.pushPathByName("PageOne", "PageOne Param")
- 带返回回调的跳转,跳转时添加onPop回调,能在页面出栈时获取返回信息,并进行处理。
this.pageStack.pushPathByName('PageOne', "PageOne Param", (popInfo) => {
console.log('Pop page name is: ' + popInfo.info.name + ', result: ' + JSON.stringify(popInfo.result))
});
- 带错误码的跳转,跳转结束会触发异步回调,返回错误码信息。
this.pageStack.pushDestinationByName('PageOne', "PageOne Param")
.catch((error: BusinessError) => {
    console.error(`Push destination failed, error code = ${error.code}, error.message = ${error.message}.`);
}).then(() => {
console.error('Push destination succeed.');
});
页面返回
// 返回到上一页
this.pageStack.pop()
// 返回到上一个PageOne页面
this.pageStack.popToName("PageOne")
// 返回到索引为1的页面
this.pageStack.popToIndex(1)
// 返回到根首页(清除栈中所有页面)
this.pageStack.clear()
页面替换
this.pageStack.replacePathByName("PageOne", "PageOne Param")
页面删除
// 删除栈中name为PageOne的所有页面
this.pageStack.removeByName("PageOne")
// 删除指定索引的页面
this.pageStack.removeByIndexes([1,3,5])
页面参数获取
// 获取栈中所有页面name集合
this.pageStack.getAllPathName()
// 获取索引为1的页面参数
this.pageStack.getParamByIndex(1)
// 获取PageOne页面的参数
this.pageStack.getParamByName("PageOne")
// 获取PageOne页面的索引集合
this.pageStack.getIndexByName("PageOne")
页面转场
Navigation默认提供了页面切换的转场动画,通过页面栈操作时,会触发不同的转场效果(Dialog类型的页面默认无转场动画),Navigation也提供了关闭系统转场、自定义转场以及共享元素转场的能力。
关闭转场
- 全局关闭
pageStack: NavPathStack = new NavPathStack()
aboutToAppear(): void {
  this.pageStack.disableAnimation(true)
}
- 单次关闭
pageStack: NavPathStack = new NavPathStack()
this.pageStack.pushPath({ name: "PageOne" }, false)
this.pageStack.pop(false)
子页面显示类型
- 标准类型(NavDestinationMode.STANDARD),生命周期跟随其在NavPathStack页面栈中的位置变化而改变。
- 弹窗类型(NavDestinationMode.DIALOG),显示和消失时不会影响下层标准类型的NavDestination的显示和生命周期,两者可以同时显示。
子页面生命周期(NavDestination)

- aboutToAppear:在创建自定义组件后,执行其build()函数之前执行(NavDestination创建之前),允许在该方法中改变状态变量,更改将在后续执行build()函数中生效。
- onWillAppear:NavDestination创建后,挂载到组件树之前执行,在该方法中更改状态变量会在当前帧显示生效。
- onAppear:通用生命周期事件,NavDestination组件挂载到组件树时执行。
- onWillShow:NavDestination组件布局显示之前执行,此时页面不可见(应用切换到前台不会触发)。
- onShown:NavDestination组件布局显示之后执行,此时页面已完成布局。
- onWillHide:NavDestination组件触发隐藏之前执行(应用切换到后台不会触发)。
- onHidden:NavDestination组件触发隐藏后执行(非栈顶页面push进栈,栈顶页面pop出栈或应用切换到后台)。
- onWillDisappear:NavDestination组件即将销毁之前执行,如果有转场动画,会在动画前触发(栈顶页面pop出栈)。
- onDisappear:通用生命周期事件,NavDestination组件从组件树上卸载销毁时执行。
- aboutToDisappear:自定义组件析构销毁之前执行,不允许在该方法中改变状态变量。
使用案例
实现简单的登录界面跳转。
 
项目目录

Index
import { component_1 } from '../Components/component_1';
import { component_2 } from '../Components/component_2';
import { LoginParam } from '../Models/LoginParam';
@Entry
@Component
struct Index {
  @Provide("pageNavigation") pageNav: NavPathStack = new NavPathStack();
  @Builder
  PageMap(path: string) {
    if (path == "component_1") {
      component_1()
    }
    if (path == "component_2") {
      component_2()
    }
  }
  build() {
    Column() {
      Navigation(this.pageNav) {
        Button("直接跳转component_1界面(不带参数)")
          .width("80%")
          .margin({ bottom: 20 })
          .onClick(() => {
            this.pageNav.pushPathByName("component_1", "")
          })
        Button("直接跳转component_1界面(带参数)")
          .width("80%")
          .margin({ bottom: 20 })
          .onClick(() => {
            let login: LoginParam = new LoginParam("张三", "1234567");
            this.pageNav.pushPathByName("component_1", login)
          })
      }
      .title("主页")
      .titleMode(NavigationTitleMode.Full)
      .mode(NavigationMode.Auto)
      .navDestination(this.PageMap)
    }
    .height('100%')
    .width('100%')
  }
}
component_1
import { LoginParam } from '../Models/LoginParam';
import { JSON } from '@kit.ArkTS';
@Component
export struct component_1 {
  @Consume("pageNavigation") pageNav: NavPathStack;
  @State login: LoginParam = new LoginParam("", "")
  build() {
    Column() {
      NavDestination() {
        Row() {
          Text("账户:")
            .fontSize(16)
            .margin({ left: 10, right: 10 })
          TextInput({ text: this.login.Name, placeholder: "请输入账户" })
            .layoutWeight(1)
            .margin({ right: 10 })
            .onChange((value) => {
              this.login.Name = value
            })
        }
        .width("100%")
        Row() {
          Text("密码:")
            .fontSize(16)
            .margin({ left: 10, right: 10 })
          TextInput({ text: this.login.Password, placeholder: "请输入密码" })
            .layoutWeight(1)
            .margin({ right: 10 })
            .type(InputType.Password)
            .onChange((value) => {
              this.login.Password = value
            })
        }
        .width("100%")
        .margin({ top: 20 })
        Grid() {
          GridItem() {
            Button("注册")
              .width("100%")
              .backgroundColor("#f1f2f3")
              .fontColor("#007dfe")
              .onClick(() => {
                this.pageNav.pushPathByName("component_2", this.login.Name, (popInfo) => {
                  if (popInfo.result != null) {
                    let popLogin: LoginParam = popInfo.result as LoginParam;
                    if (popLogin == null) {
                      return;
                    }
                    this.login = popLogin;
                  }
                });
              })
          }
          .width("50%")
          .padding({ right: 10, left: 10 })
          GridItem() {
            Button("登录")
              .width("100%")
              .onClick(() => {
                console.log(JSON.stringify(this.login))
              })
          }
          .width("50%")
          .padding({ right: 10, left: 10 })
        }
        .rowsTemplate("1tf 1tf")
        .margin({ top: 10 })
        .width("100%")
        .height(60)
      }
      .title("登录")
      .mode(NavDestinationMode.STANDARD)
      .onWillShow(() => {
        let tempPara: LoginParam[] | string[] = this.pageNav.getParamByName("component_1") as LoginParam[] | string[]
        if (tempPara.length == 0 || tempPara[0] == "") {
          return;
        }
        this.login = tempPara[0] as LoginParam
      })
    }
    .width("100%")
    .height("100%")
  }
}
component_2
import { LoginParam } from '../Models/LoginParam'
import { promptAction } from '@kit.ArkUI';
@Component
export struct component_2 {
  @Consume("pageNavigation") pageNav: NavPathStack;
  @State login: LoginParam = new LoginParam("", "");
  @State tempPassword: string = "";
  build() {
    Column() {
      NavDestination() {
        Row() {
          Text("账户:")
            .fontSize(16)
            .margin({ left: 10, right: 10 })
            .width(40)
          TextInput({ text: this.login.Name, placeholder: "请输入账户" })
            .layoutWeight(1)
            .margin({ right: 10 })
            .onChange((value) => {
              this.login.Name = value
            })
        }
        .width("100%")
        Row() {
          Text("密码:")
            .fontSize(16)
            .margin({ left: 10, right: 10 })
            .width(40)
          TextInput({ text: this.login.Password, placeholder: "请输入密码" })
            .layoutWeight(1)
            .margin({ right: 10 })
            .type(InputType.Password)
            .onChange((value) => {
              this.login.Password = value
            })
        }
        .width("100%")
        .margin({ top: 20 })
        Row() {
          Text("确认密码:")
            .fontSize(16)
            .margin({ left: 10, right: 10 })
            .width(40)
          TextInput({ text: $$this.tempPassword, placeholder: "请再次输入密码" })
            .layoutWeight(1)
            .margin({ right: 10 })
            .type(InputType.Password)
            .onChange((value) => {
              this.tempPassword = value
            })
        }
        .width("100%")
        .margin({ top: 20 })
        Column() {
          Button("注册")
            .width("100%")
            .onClick(() => {
              if (this.tempPassword != "" && this.tempPassword === this.login.Password && this.login.Name != "") {
                this.pageNav.pop(this.login)
              } else {
                promptAction.showDialog({
                  title: "提示",
                  message: "注册失败,密码不一致或账户为空",
                  buttons: [
                    {
                      text: "确认",
                      color: "#000"
                    }
                  ]
                })
              }
            })
        }
        .width("100%")
        .margin({ top: 20 })
        .padding({ right: 10, left: 10 })
      }
      .title("注册")
      .mode(NavDestinationMode.STANDARD)
      .onWillShow(() => {
        let names: string[] = this.pageNav.getParamByName("component_2") as string[];
        if (names == null || names.length === 0) {
          return;
        }
        this.login.Name = names[0]
      })
    }
    .width("100%")
    .height("100%")
  }
}
LoginParam
@Observed
export class LoginParam {
  Name: string = "";
  Password: string = "";
  constructor(name: string, password: string) {
    this.Name = name;
    this.Password = password;
  }
}



















