import { uiObserver } from '@kit.ArkUI'; function callBackFunc(info: uiObserver.NavDestinationSwitchInfo) { let from = JSON.stringify(info.from); let to = JSON.stringify(info.to); console.info(`from:${from} to: ${to}`); } @Entry @Component struct NavObserverDemo { private stack: NavPathStack = new NavPathStack(); @Builder Page() { PageOne(); } aboutToAppear() { uiObserver.on('navDestinationSwitch', this.getUIContext(), callBackFunc); // 注册页面切换的监听 } aboutToDisappear() { uiObserver.off('navDestinationSwitch', this.getUIContext(), callBackFunc); } build() { Navigation(this.stack) { Button('跳转').onClick(() => { this.stack.pushPath({ name: 'pageOne' }); }); } .title('Navigation') .navDestination(this.Page); } } @Component export struct PageOne { build() { NavDestination() { Text('pageOne'); }.title('pageOne'); } }
@Entry @Component struct Index1 { pathStack: NavPathStack = new NavPathStack(); aboutToAppear(): void { this.pathStack.setInterception({ willShow: (from: NavDestinationContext | 'navBar', to: NavDestinationContext | 'navBar') => { if (typeof from === 'string') { let target = to as NavDestinationContext; console.info(`from page is navigation home -> ${target.pathInfo.name}`); } else if (typeof to === 'string') { let target = from as NavDestinationContext; console.info(`${target.pathInfo.name} -> to page is navigation home`); } } }); } @Builder pageMap() { PageOne(); } build() { Navigation(this.pathStack) { Column({ space: 30 }) { Text('PageOne'); Button('跳转') .onClick(() => { this.pathStack.pushPathByName('PageOne', null, false); }); }; }.navDestination(this.pageMap); } } @Component struct PageOne { pathStack: NavPathStack = new NavPathStack(); build() { NavDestination() { Column({ space: 30 }) { Text('PageOne'); Button('跳转') .onClick(() => { this.pathStack.pop(); }); }; }.title('PageOne') .onReady((context: NavDestinationContext) => { this.pathStack = context.pathStack; }); } }
Q:无感监听有哪些常见事件?
A:监听滚动事件uiObserver.on('scrollEvent')、监听NavDestination组件的状态变化uiObserver.on('navDestinationUpdate')、监听TabContent页面的切换事件uiObserver.on('tabContentUpdate')等。