新建页面
我们右键pages文件夹,新建ArkTs文件
同时也需要配置第二个页面的路由
打开entry > src > main > resources > base > profile 中的 main_pages.json,并配置路由
{
"src": [
"pages/Index",
"pages/Second"
]
}
我们参考第一个页面去完成第二个简单的页面
// Second.ets
@Entry
@Component
struct Second {
@State message: string = '第二个页面'
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
Button() {
Text('Back')
.fontSize(25)
.fontWeight(FontWeight.Bold)
}
.type(ButtonType.Capsule)
.margin({
top: 20
})
.backgroundColor('#0D9FFB')
.width('40%')
.height('5%')
}
.width('100%')
}
.height('100%')
}
}
路由跳转
接下来就需要实现路由的跳转了
我们需要在第一个页面(index.ets)中导入路由模块
// 导入页面路由模块
import router from '@ohos.router';
并给按钮添加点击事件
// 跳转按钮绑定onClick事件,点击时跳转到第二页
.onClick(() => {
console.info(`Succeeded in clicking the 'Next' button.`)
// 跳转到第二页
router.pushUrl({ url: 'pages/Second' }).then(() => {
console.info('Succeeded in jumping to the second page.')
}).catch((err) => {
console.error(`Failed to jump to the second page.Code is ${err.code}, message is ${err.message}`)
})
})
通过.then 和 .catch 执行成功或失败后的操作
点击按钮,就可以跳转到我们刚刚编写的第二个页面了
反之,我们也可以给第二个页面的按钮添加点击事件,让应用返回到第一个页面
还是添加一下代码即可实现
// 导入页面路由模块
import router from '@ohos.router';
.onClick(() => {
console.info(`Succeeded in clicking the 'Back' button.`)
try {
// 返回第一页
router.back()
console.info('Succeeded in returning to the first page.')
} catch (err) {
console.error(`Failed to return to the first page.Code is ${err.code}, message is ${err.message}`)
}
})
最后咱们可以在模拟器中运行,查看交互效果