【使用onPageshow等生命周期函数】
在entry/src/main/ets/pages路径下创建Page1.ets:
import router from '@ohos.router' @Entry @Component struct Page1 { @State message: string = 'Hello World' @State show: boolean=true aboutToAppear(){ console.log('Page1组件创建实例') } aboutToDisappear(){ console.log('Page1组件销毁') } onPageShow(){ console.log('page1页面展示') } onPageHide(){ console.log("page1页面隐藏") } build() { Column() { Button('show') .onClick(()=>{ this.show=!this.show }) if (this.show){ ComponentA() } Button('跳转到Page2') .onClick(()=>{ router.pushUrl({url:"pages/Page2"}) }) Button('跳转到Page3') .onClick(()=>{ router.replaceUrl({url:"pages/Page3"}) }) } .width('100%') .height('100%') } } @Component struct ComponentA{ aboutToAppear(){ console.log('componentA组件创建实例') } aboutToDisappear(){ console.log('componentA组件销毁'); } build(){ Text('compontent A') } }
在entry/src/main/ets/pages路径下同样创建Page2.ets和Page3.ets:
1.Page2.ets内容:
@Entry @Component struct Page2 { @State message: string = 'Page2内容' onPageShow(){ console.log('page2页面展示') } onPageHide(){ console.log("page2页面隐藏") } onBackPress(){ console.log("Page2页面返回") } build() { Row() { Column() { Text(this.message) .fontSize(50) .fontWeight(FontWeight.Bold) } .width('100%') } .height('100%') } }
2.Page3.ets内容:
@Entry @Component struct Page3 { @State message: string = 'Page3内容' onPageShow(){ console.log('page3页面展示') } onPageHide(){ console.log("page3页面隐藏") } build() { Row() { Column() { Text(this.message) .fontSize(50) .fontWeight(FontWeight.Bold) } .width('100%') } .height('100%') } }
在下边点击Log->HiLog,中间最左边的下拉菜单选择Phone,查看效果,如图: