目录

Navigation如何获取页面名称

问题现象

Navigation路由跳转场景下,如何获取当前所在页面的页面名称或者信息?

背景知识

解决方案

获取页面名称的方案有三种:

Navigation页面:

import { NaviDesPagBuilder } from './SubPage';

@Entry
@Component
struct Index {
  navPathStack: NavPathStack = new NavPathStack();

  aboutToAppear(): void {
    // 通过setInterception跳转拦截获取目标页面名称
    this.navPathStack.setInterception({
      willShow: (from: NavDestinationContext | 'navBar', to: NavDestinationContext | 'navBar') => {
        if (typeof from === 'string') {
          console.info(`from: ${from}`);
        }
        if (typeof to === 'string') {
          console.info('target page is navigation home');
          return;
        }
        let target: NavDestinationContext = to as NavDestinationContext;
        console.info(`setInterception currentPageName = ${target.pathInfo.name}`);
      }
    });
  }

  @Builder
  pageMap(name: string) {
    if (name === 'GetNaviPageName_NaviDesPage') {
      NaviDesPagBuilder();
    }
  }

  build() {
    Navigation(this.navPathStack) {
      Button('跳转NavDestination')
        .fontSize('20fp')
        .margin({ top: '50vp' })
        .onClick(() => {
          this.navPathStack.pushPath({ name: 'GetNaviPageName_NaviDesPage' });
        });
    }.navDestination(this.pageMap)
    .height('100%')
    .width('100%');
  }
}

NavDestination页面:

@Builder
export function NaviDesPagBuilder() {
  GetNaviPageName_NaviDesPage();
}

@Entry
@Component
struct GetNaviPageName_NaviDesPage {
  navPathStack: NavPathStack = new NavPathStack();

  build() {
    NavDestination() {
      Button('GetName')
        .onClick(() => {
          // 调用getAllPageName,拿到所有页面名字,最后一项即为当前页面名称
          let names = this.navPathStack.getAllPathName();
          let pageName = names[names.length-1];
          console.info(`last page of getAllPathName: ${pageName}`);
        });
    }
    .onReady((ctx: NavDestinationContext) => {
      // 通过onReady回调的NavDestinationContext获取当前页面名称
      this.navPathStack = ctx.pathStack;
      console.info(`onReady: ${ctx.pathInfo.name}`);
    }).height('100%').width('100%');
  }
}

常见FAQ

Q:Navigation获取页面参数getParamByName获取的返回值为什么是Array?

A:getParamByName是路由栈NavPathStack的实例方法,路由栈中一个页面可以入栈多次。例如在页面A中push一个页面A,此时路由栈中就有两个页面A,每次跳转到页面A可能携带不同的参数,所以getParamByName方法的返回值是数组。