鸿蒙Next router在features模块如何注册

在鸿蒙Next开发中,如何在features模块注册router?我按照官方文档尝试了@ohos.router的API,但路由跳转始终不生效。是否需要额外配置路由表或声明权限?求具体代码示例和模块依赖的完整配置步骤。

2 回复

鸿蒙Next里注册路由?简单!在features模块的resources/base/profile/router_map.json里,像填菜单一样加路由配置就行。记得路径别写错,不然应用会迷路哦~(手动狗头)

更多关于鸿蒙Next router在features模块如何注册的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在鸿蒙Next中,在features模块注册router,需要在模块的build-profile.json5文件中配置路由信息,并在代码中定义路由页面。

步骤:

  1. build-profile.json5中注册路由: 在features模块的build-profile.json5文件中添加router配置,指定页面路由路径和对应的Ability名称。

    {
      "app": {
        "signingConfigs": [],
        "products": []
      },
      "modules": [
        {
          "name": "feature",
          "srcEntry": "./src/main/ets",
          "router": {
            "entry": "pages/Index", // 路由入口页面
            "pages": {
              "pages/Index": {
                "name": "index",
                "ability": ".MainAbility" // 对应的Ability
              },
              "pages/Detail": {
                "name": "detail",
                "ability": ".MainAbility"
              }
            }
          }
        }
      ]
    }
    
  2. 在代码中定义页面路由:src/main/ets/router目录下(如无则创建),创建RouterMap.ets文件,定义路由映射。

    import { RouterMap } from '[@ohos](/user/ohos).router';
    
    export const routerMap: RouterMap = {
      'index': {
        bundleName: 'com.example.myapp',
        abilityName: '.MainAbility',
        uri: 'pages/Index'
      },
      'detail': {
        bundleName: 'com.example.myapp',
        abilityName: '.MainAbility',
        uri: 'pages/Detail'
      }
    };
    
  3. 在Ability中加载路由: 在MainAbility的onWindowStageCreate方法中加载路由配置。

    import { Ability, router } from '[@ohos](/user/ohos).ability.abilityRuntime';
    import { routerMap } from '../router/RouterMap';
    
    export default class MainAbility extends Ability {
      onWindowStageCreate(windowStage) {
        router.loadRouter(routerMap);
        windowStage.loadContent('pages/Index');
      }
    }
    

说明:

  • 确保路径和Ability名称与项目实际结构一致。
  • 使用router.pushUrl()router.replaceUrl()进行页面跳转。

完成以上配置后,即可在features模块中正常使用router进行页面导航。

回到顶部