获取页面名称的方案有三种:
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%'); } }