11-鸿蒙4.0学习之页面之间的参数传递
方法一
params
// 传参页面
import router from '@ohos.router'@Entry
@Component
struct LifeCycle1 {@State message: string = 'Hello World'@State isShow: boolean = falsebuild() {Row() {Column({ space: 20 }) {Text(this.message).fontSize(50).fontWeight(FontWeight.Bold)Button('跳转界面').onClick(() => {router.pushUrl({url: 'pages/LifeCycle2',params:{name:'小明',age:20}})})Button('切换').onClick(() => {this.isShow = !this.isShow})Divider()if (this.isShow) {LifeCycle1_son()}}.width('100%')}.height('100%')}// 页面显示onPageShow() {console.log('page1……onPageShow')}// 页面隐藏onPageHide() {console.log('page1……onPageHide')}// 页面返回onBackPress() {console.log('page1……onBackPress')}aboutToAppear() {console.log('组件本身……aboutToAppear')}// 组件析构销毁时触发:删除 移出aboutToDisappear() {console.log('组件本身……aboutToDisappear')}
}@Component
struct LifeCycle1_son {build() {Column() {Text('子组件').fontSize(50)}}// 组件渲染之前aboutToAppear() {console.log('LifeCycle1_son……aboutToAppear')}// 组件析构销毁时触发:删除 移出aboutToDisappear() {console.log('LifeCycle1_son……aboutToDisappear')}
}
接受参数页面
import router from '@ohos.router'let name = router.getParams()['name'] as string@Entry
@Component
struct LifeCycle2 {@State message: string = 'Hello World'build() {Row() {Column() {Text(name).fontSize(50)Text(this.message).fontSize(50).fontWeight(FontWeight.Bold)Button('返回第一个页面').onClick(() => {router.back()})}.width('100%')}.height('100%')}// 页面显示onPageShow(){console.log('page2……onPageShow')}// 页面隐藏onPageHide(){console.log('page2……onPageHide')}// 页面返回onBackPress(){console.log('page2……onBackPress')}
}
// 应用程序之间数据共享
// AppStorage.Set(‘appName’,‘我是应用程序’)
AppStorage.SetOrCreate(‘appName’,‘我是应用程序所存储的数据’)
// 从应用对象身上取出数据
let appName:string = AppStorage.Get(‘appName’) as string
// 模拟器获取不到,真机可以显示出来