鸿蒙HarmonyOS NEXT--Navigation和router处理页面间的数据传递

HarmonyOS NEXT 5.0 中,页面间的数据传递可以有很多种方式,这里用的Navigationrouter

1. 使用Navigation组件传递参数

在HarmonyOS NEXT中,可以通过Navigation组件的NavPathInfo对象来实现页面间的数据传递。以下是具体的步骤和代码示例:

Step 1: 在发起页面构建NavPathInfo对象,并输入需要传递给目标页面的参数。

// 发起页 mainPage
let loginParam : LoginParam = new LoginParam();
// 构建pathInfo对象
let pathInfo : NavPathInfo = new NavPathInfo('loginPage', loginParam, (popInfo: PopInfo) => {
  let loginParam : LoginParam = popInfo.info.param as LoginParam;
  // 处理返回的数据
});
// 将参数传递到目标页
this.pageStack.pushDestination(pathInfo, true);

Step 2: 在目标页面通过NavPathStack.getParamByIndex(0)获取到发起页传递过来的参数。

@Component
export struct loginPageView {
  @Consume('pageInfo') pageStack : NavPathStack;
  aboutToAppear(): void {
    this.loginParam = this.pageStack.getParamByIndex(0) as LoginParam;
  }
  // 使用loginParam进行后续操作
}

Step 3: 目标页通过NavPathStack.pop方法返回起始页,其result参数用来传递需要返回给起始页的对象。

@Component
export struct loginPageView {
  @Consume('pageInfo') pageStack : NavPathStack;
  // 页面构建的对象
  private loginParam! : LoginParam;
  ...
  build() {
    NavDestination(){
      ...
      Button('login').onClick( ent => {
        // 将对象返回给起始页
        this.pageStack.pop(this.loginParam, true)
      })
    }
  }
}

业务场景案例演示

下面通过一个简单的业务场景来演示如何使用Navigation组件在HarmonyOS NEXT中传递参数。我们来创建一个简单的应用,包含两个页面:一个主页面(HomePage)和一个详情页面(DetailPage)。用户在主页面点击一个列表项时,应用将传递该项的ID到详情页面,并在详情页面显示对应的信息。

1. 主页面(HomePage.ets)

首先,我们创建主页面,其中包含一个列表,每个列表项点击时都会传递其ID到详情页面。

import { Column, Text, Navigation, Button } from '@ohos.arkui';
import { NavPathInfo } from '@ohos.application';

@Component
struct HomePage {
  private items: Array<{ id: number; name: string }> = [
    { id: 1, name: '刘备' },
    { id: 2, name: '关羽' },
    { id: 3, name: '张飞' },
  ];

  build() {
    Column() {
      this.items.map((item) => {
        return Column() {
          Button(item.name)
            .onClick(() => {
              this.navigateToDetail(item.id);
            });
        };
      });
    }
  }

  private navigateToDetail(id: number): void {
    const navInfo = new NavPathInfo({
      uri: 'pages/detail/DetailPage',
      params: { id },
    });
    Navigation.push(navInfo);
  }
}

2. 详情页面(DetailPage.ets)

接下来,我们创建详情页面,它将接收从主页面传递过来的ID,并显示相应的信息。

import { Column, Text } from '@ohos.arkui';
import { Navigation } from '@ohos.application';

@Component
struct DetailPage {
  @State private id: number = 0;

  aboutToAppear() {
    this.id = Navigation.getParams().id;
  }

  build() {
    Column() {
      Text(`Detail Page for ID: ${this.id}`);
    }
  }
}

代码解释

  1. HomePage:

    • 我们定义了一个items数组,包含一些示例数据。
    • build方法中,我们使用ColumnButton组件创建了一个按钮列表,每个按钮显示一个项目名称。
    • 当按钮被点击时,navigateToDetail方法被调用,它创建一个新的NavPathInfo对象,其中包含目标页面的URI和要传递的参数(在这个例子中是项目的ID)。
    • 使用Navigation.push方法,我们将NavPathInfo对象传递给Navigation组件,从而导航到详情页面。
  2. DetailPage:

    • DetailPage中,我们使用@State装饰器定义了一个id状态变量,用于存储从主页面传递过来的ID。
    • aboutToAppear生命周期方法中,我们通过Navigation.getParams()获取传递过来的参数,并将其赋值给id状态变量。
    • build方法中,我们使用ColumnText组件显示传递过来的ID。

通过这个案例展示了如何在HarmonyOS NEXT中使用Navigation组件在页面间传递参数。通过这种方式,可以轻松地在应用的不同页面之间共享数据。

2. 使用router传递参数

除了Navigation,咱们常用的另一种方式是通过router对象进行页面跳转和参数传递。来看一下具体的步骤和代码示例:

发起页面:

import { router } from '@kit.ArkUI';
// 准备跳转的参数
let paramsInfo: DataModel = {
  id: 123456,
  info: {
    age: 18
  }
};
// 执行跳转并传递参数
router.pushUrl({
  url: 'pages/routertest/Page2',
  params: paramsInfo
}, (err) => {
  if (err) {
    console.error(`Invoke pushUrl failed, code is ${err.code}, message is ${err.message}`);
    return;
  }
  console.info('Invoke pushUrl succeeded.');
});

目标页面:

import { router } from '@kit.ArkUI';
import { DataModel } from './DataModels'

@Entry
@Component
struct Page2 {
  @State receivedParams: DataModel = {} as DataModel;

  aboutToAppear() {
    this.receivedParams = router.getParams() as DataModel;
    console.info('Received params:', this.receivedParams);
  }
  
  build() {
    Column() {
      Text(`Received ID: ${this.receivedParams.id}`)
      Text(`Received Age: ${this.receivedParams.info.age}`)
    }
  }
}

来看一个业务场景

假设我们有这样一个业务场景,一个包含两个页面的应用:一个商品列表页面(ProductListPage)和一个商品详情页面(ProductDetailPage)。用户在商品列表页面点击某个商品时,应用将传递该商品的ID到商品详情页面,并在详情页面显示对应的信息。

1. 商品列表页面(ProductListPage.ets)

首先,我们创建商品列表页面,其中包含一个商品列表,每个列表项点击时都会传递其ID到商品详情页面。

import { Column, Text, router } from '@ohos.arkui';

@Component
struct ProductListPage {
  private products: Array<{ id: number; name: string }> = [
    { id: 1, name: '苹果' },
    { id: 2, name: '百香果' },
    { id: 3, name: '香蕉' },
  ];

  build() {
    Column() {
      this.products.map((product) => {
        return Column() {
          Text(product.name)
            .width('100%')
            .height(50)
            .onClick(() => {
              this.navigateToDetail(product.id);
            });
        };
      });
    }
  }

  private navigateToDetail(id: number): void {
    router.push({
      url: 'pages/productDetail/ProductDetailPage',
      params: { id },
    });
  }
}

2. 商品详情页面(ProductDetailPage.ets)

接下来,我们创建商品详情页面,它将接收从商品列表页面传递过来的ID,并显示相应的信息。

import { Column, Text, router } from '@ohos.arkui';

@Component
struct ProductDetailPage {
  @State private id: number = 0;

  aboutToAppear() {
    this.id = router.getParams().id;
  }

  build() {
    Column() {
      Text(`Product Detail for ID: ${this.id}`);
    }
  }
}

代码解释

  1. ProductListPage:

    • 我们定义了一个products数组,包含一些示例商品数据。
    • build方法中,我们使用ColumnText组件创建了一个商品列表,每个商品项显示商品名称。
    • 当商品项被点击时,navigateToDetail方法被调用,它使用router.push方法将商品ID作为参数传递给商品详情页面。
    • router.push方法接受一个对象,其中包含目标页面的URL和要传递的参数。
  2. ProductDetailPage:

    • ProductDetailPage中,我们使用@State装饰器定义了一个id状态变量,用于存储从商品列表页面传递过来的ID。
    • aboutToAppear生命周期方法中,我们通过router.getParams()获取传递过来的参数,并将其赋值给id状态变量。
    • build方法中,我们使用ColumnText组件显示传递过来的ID。

使用router在页面间传递参数,可以说是最最常用的方式了,通过这种方式,我们可以轻松地在应用的不同页面之间共享数据。

最后

以上两种方法都可以实现HarmonyOS NEXT中页面间的数据传递。第一种方法通过Navigation组件实现,适用于组件导航的场景;第二种方法通过router对象实现,适用于基于URL的页面跳转场景。

鸿蒙操作系统(HarmonyOS)中,Navigation路由跳转是一种常用的页面导航方式。它允许开发者在不同的页面进行导航传递数据。以下是鸿蒙Navigation路由跳转的用法: ### 1. 配置路由表 首先,需要在`config.json`文件中配置路由表,定义各个页面的路由路径。 ```json { "routes": [ { "uri": "pages/page1", "moduleName": "com.example.myapplication.Page1AbilitySlice" }, { "uri": "pages/page2", "moduleName": "com.example.myapplication.Page2AbilitySlice" } ] } ``` ### 2. 使用Navigation接口进行跳转 在代码中使用`Navigation`接口进行页面跳转。 ```java import ohos.app.Context; import ohos.app.dispatcher.task.TaskPriority; import ohos.global.resource.NotExistException; import ohos.global.resource.Resource; import ohos.global.resource.ResourceManager; import ohos.global.resource.WrongTypeException; import ohos.agp.components.Button; import ohos.agp.components.Component; import ohos.agp.components.Component.ClickedListener; import ohos.agp.window.dialog.ToastDialog; import ohos.app.AbilitySlice; import ohos.app.dispatcher.Dispatcher; import ohos.app.dispatcher.DispatcherPriority; import ohos.app.dispatcher.IRemoteObject; public class Page1AbilitySlice extends AbilitySlice { @Override public void onStart(Intent intent) { super.onStart(intent); super.setUIContent(ResourceTable.Layout_ability_page1); Button button = (Button) findComponentById(ResourceTable.Id_button); button.setClickedListener(new ClickedListener() { @Override public void onClick(Component component) { Intent intent = new Intent(); Operation operation = new Intent.OperationBuilder() .withDeviceId("") .withBundleName("com.example.myapplication") .withAbilityName("com.example.myapplication.Page2Ability") .withAction("action.example.page2") .build(); intent.setOperation(operation); startAbility(intent); } }); } } ``` ### 3. 传递数据 在跳转时,可以通过`Intent`对象传递数据。 ```java Intent intent = new Intent(); intent.setParam("key", "value"); startAbility(intent); ``` 在目标页面中接收数据: ```java @Override public void onStart(Intent intent) { super.onStart(intent); String value = intent.getStringParam("key"); // 使用传递数据 } ``` ### 4. 返回上一页 在目标页面中使用`terminateAbility`方法返回上一页。 ```java Button backButton = (Button) findComponentById(ResourceTable.Id_back_button); backButton.setClickedListener(new ClickedListener() { @Override public void onClick(Component component) { terminateAbility(); } }); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值