鸿蒙路由参数传递
页面test.ets
代码如下:
import router from '@ohos.router'
@Entry
@Component
struct Test {@State message: string = 'Hello World'@State username: string = 'hu'@State password: string = '1'build() {Row() {Column() {Text(this.message).fontSize(50).fontWeight(FontWeight.Bold).onClick(() => {router.pushUrl({url: "pages/mine/MinePage",params: {username: this.username,password: this.password}})})}.width('100%')}.height('100%')}
}
页面MinePage.ets如下:
import router from '@ohos.router'@Entry
@Component
struct MinePage {@State username: string = ''@State password: string = ''aboutToAppear() {try {const params = router.getParams() as { username?: string; password?: string }// ✅ 判断 username 是否存在且不为空字符串if (params.username && params.username !== '') {this.username = params.usernamethis.password = params.password ?? ''}} catch (e) {console.warn('router.getParams 在预览模式不可用,已跳过参数获取')}}build() {Column() {Text(`欢迎你,${this.username}`)Text(`你的密码是:${this.password}`).onClick(()=>{router.pushUrl({url:'pages/test'})})}.padding(20)}
}
运行结果如下: