文档开发者中心
我的
|

HarmonyOS 5

HarmonyOS如何实现页面跳转和参数传递?router的完整使用方法

问题描述

- HarmonyOS 5.0,DevEco Studio 5.0

- 需要从列表页跳转到详情页,并传递数据

- 不清楚router的具体用法和参数获取方式

希望了解router的完整使用方法,包括跳转、传参、返回等操作

点赞
收藏
回复
1
分享
举报
浏览93 发布于2025-12-25 07:39未知归属地
全部评论
最多点赞
最新发布
最早发布
收起
自动换行
深色代码主题
复制
## 解决方案

### 1. 导入router模块

```typescript
import router from '@ohos.router'
```

### 2. 基础页面跳转

```typescript
// 方式1:pushUrl - 跳转到新页面(保留当前页面在栈中)
router.pushUrl({
  url: 'pages/DetailPage'
})

// 方式2:replaceUrl - 替换当前页面(不保留当前页面)
router.replaceUrl({
  url: 'pages/DetailPage'
})
```

### 3. 带参数跳转

```typescript
// 列表页 - 跳转并传递参数
@Entry
@Component
struct ListPage {
  
  goToDetail(item: ItemData) {
    router.pushUrl({
      url: 'pages/DetailPage',
      params: {
        id: item.id,
        title: item.title,
        data: item  // 可以传递对象
      }
    })
  }
  
  build() {
    List() {
      ForEach(this.dataList, (item: ItemData) => {
        ListItem() {
          Text(item.title)
            .onClick(() => this.goToDetail(item))
        }
      })
    }
  }
}
```

### 4. 接收页面参数

```typescript
// 定义参数类型接口
interface DetailParams {
  id: string
  title: string
  data?: ItemData
}

@Entry
@Component
struct DetailPage {
  @State itemId: string = ''
  @State itemTitle: string = ''
  
  aboutToAppear(): void {
    // 获取路由参数
    const params = router.getParams() as DetailParams
    if (params) {
      this.itemId = params.id
      this.itemTitle = params.title
      console.info('接收到参数:', JSON.stringify(params))
    }
  }
  
  build() {
    Column() {
      Text(`ID: ${this.itemId}`)
      Text(`标题: ${this.itemTitle}`)
    }
  }
}
```

### 5. 返回上一页

```typescript
// 简单返回
router.back()

// 返回并传递数据
router.back({
  url: 'pages/ListPage',
  params: {
    result: 'success',
    updatedData: this.editedData
  }
})
```

### 6. 监听返回结果

```typescript
@Entry
@Component
struct ListPage {
  
  onPageShow(): void {
    // 页面重新显示时检查返回参数
    const params = router.getParams() as ResultParams
    if (params?.result === 'success') {
      // 处理返回结果
      this.refreshData()
    }
  }
}
```

### 7. 页面配置 main_pages.json

确保目标页面已在配置文件中注册:

```json
{
  "src": [
    "pages/Index",
    "pages/ListPage",
    "pages/DetailPage",
    "pages/EditPage"
  ]
}
```

### 8. 完整示例

**列表页 ListPage.ets:**
```typescript
import router from '@ohos.router'

interface ItemData {
  id: string
  title: string
  content: string
}

@Entry
@Component
struct ListPage {
  @State dataList: ItemData[] = [
    { id: '1', title: '项目一', content: '内容一' },
    { id: '2', title: '项目二', content: '内容二' }
  ]
  
  build() {
    Navigation() {
      List({ space: 12 }) {
        ForEach(this.dataList, (item: ItemData) => {
          ListItem() {
            Row() {
              Text(item.title)
                .fontSize(16)
              Blank()
              Image($r('app.media.ic_arrow_right'))
                .width(20)
                .height(20)
            }
            .width('100%')
            .padding(16)
            .backgroundColor('#FFFFFF')
            .borderRadius(8)
            .onClick(() => {
              router.pushUrl({
                url: 'pages/DetailPage',
                params: { id: item.id, title: item.title, content: item.content }
              })
            })
          }
        }, (item: ItemData) => item.id)
      }
      .padding(16)
    }
    .title('列表')
  }
}
```

**详情页 DetailPage.ets:**
```typescript
import router from '@ohos.router'

interface DetailParams {
  id: string
  title: string
  content: string
}

@Entry
@Component
struct DetailPage {
  @State params: DetailParams = { id: '', title: '', content: '' }
  
  aboutToAppear(): void {
    const routerParams = router.getParams() as DetailParams
    if (routerParams) {
      this.params = routerParams
    }
  }
  
  build() {
    Navigation() {
      Column({ space: 16 }) {
        Text(this.params.title)
          .fontSize(24)
          .fontWeight(FontWeight.Bold)
        Text(this.params.content)
          .fontSize(16)
        
        Button('返回')
          .onClick(() => router.back())
      }
      .padding(16)
    }
    .title('详情')
  }
}

### 9. 路由模式对比

| 方法 | 说明 | 页面栈变化 |

|------|------|-----------|

| `pushUrl` | 跳转新页面 | A → A, B |

| `replaceUrl` | 替换当前页面 | A → B |

| `back` | 返回上一页 | A, B → A |

| `clear` | 清空页面栈 | A, B, C → 空 |

---

**注意事项:**

1. 传递的参数对象会被序列化,不要传递函数或循环引用对象

2. 页面必须在 main_pages.json 中注册

3. 使用 TypeScript 接口定义参数类型,避免类型错误

抱歉,暂时无法回复!

展开全部
1楼回复于2025-12-25 09:06 未知归属地
写回答
新增插入模板功能
一键使用模板,快速填写内容,轻松发帖~
知道了
  • 为了保障您的信息安全,请勿上传您的敏感个人信息(如您的密码等信息)和您的敏感资产信息(如关键源代码、签名私钥、调试安装包、业务日志等信息),且您需自行承担由此产生的信息泄露等安全风险。
  • 如您发布的内容为转载内容,请注明内容来源。

我要提问题

了解社区公约,与您携手共创和谐专业的开发者社区。