五笔打字通主页
先创建2个页面:Page10.ets Page11.ets
这2个页面的代码如下“
import router from '@ohos.router'
//传递的参数用一个类或接口来规范
class person {
id: number = 0
name: string = ''
age: string = '0'
}
@Entry
@Component
struct Page10 {
@State idStr: string = ''
@State name: string = ''
@State age: string = ''
build() {
Column({ space: 50 }) {
Text('Page10')
.fontSize(40)
.fontWeight(FontWeight.Bold)
// Blank()
Column({ space: 50 }) {
Button('直接跳转')
.onClick(() => {
router.pushUrl({
url: 'pages/Page11'
})
})
Button('跳转,并传参数')
.onClick(() => {
router.pushUrl({
url: 'pages/Page11',
params: {
id: 3,
name: '张三',
age: '30'
}
})
})
Button('显示传过来的参数') //代码来自 wb98.com
.onClick(() => {
let aaa: person = router.getParams() as person
this.idStr = aaa.id.toString()
this.name = aaa.name
this.age = aaa.age
})
Text(this.idStr)
Text(this.name)
Text(this.age)
Button('返回')
.onClick(() => {
router.back() //跳转前必须有 url: 'pages/Page11' 才能返回
})
}
}.width('100%')
.height('100%')
.justifyContent(FlexAlign.SpaceEvenly)
}
}Page11.ets 代码如下
import router from '@ohos.router'
// 此模块为跳转传参演示
class person {
id: number = 0
name: string = ''
age: string = '0'
}
@Entry
@Component
struct Page11 {
@State idStr: string = ''
@State name: string = ''
@State age: string = ''
build() {
Column({ space: 20 }) {
Text('Page11')
.fontSize(40)
.fontWeight(FontWeight.Bold)
// Blank()
Button('显示传来的参数') //代码来自 wb86.com
.onClick(() => {
let params: person = router.getParams() as person //后面2行代码也成功
// const params = (router.getParams() || {}) as Record<string,object>
// const params = router.getParams() as Record<string | '', object>
// console.log(`name:${params['name']}`)
// console.log('这是:', JSON.stringify(params))
// console.log('这是:', params.id)
// console.log('这是:', params.name)
// console.log('这是:', params.age)
//
// const id: object = params.id // 获取id属性的值
// const strid: String = String(params.id)
// console.log('这是:', strid)
this.idStr = params.id.toString()
this.name = params.name
this.age = params.age
})
Text(this.idStr)
Text(this.name)
Text(this.age)
Button('返回前有提示')
.onClick(() => {
router.showAlertBeforeBackPage({
message: '真的要返回吗?'
})
router.back() //
//下面返回带参数的代码失败了,测试结果是,无法返回
// router.back({
// url: 'pages/page10',
// params: {
// id: 902,
// name: '方回',
// age: '88'
// }
// })
})
Button('只是返回')
.onClick(() => {
router.back() //跳转前必须有 url: 'pages/Page10' 才能返回
})
Button('带参数,直接去Page10')
.onClick(() => {
router.pushUrl({
url: 'pages/Page10',
params: {
id: 111,
name: '直接来的',
age: '66'
}
}, router.RouterMode.Single)
})
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
.padding({ top: 200, bottom: 200 })
.backgroundColor(Color.Yellow)
}
}返回带参数的代码,在测试时失败了,不知原因。我记得以前测试是成功的,难道我记错了。看官方文档,返回是可以带参数的呀。
来源:济亨网
本文链接:https://www.wb98.com/post/373.html