鸿蒙Next-集成HmRouter的路由模式

第一步:全局安装hmrouter依赖

TypeScript 复制代码
ohpm install @hadss/hmrouter

第二步:修改全局的hvigor-config.json5(加入hm-router插件)

hvigor/hvigor-config.json5

TypeScript 复制代码
{
  "modelVersion": "5.0.1",
  "dependencies": {
    "@hadss/hmrouter-plugin": "^1.0.0-rc.10"
  },
  "execution": {
    // "analyze": "normal",                     /* Define the build analyze mode. Value: [ "normal" | "advanced" | false ]. Default: "normal" */
    // "daemon": true,                          /* Enable daemon compilation. Value: [ true | false ]. Default: true */
    // "incremental": true,                     /* Enable incremental compilation. Value: [ true | false ]. Default: true */
    // "parallel": true,                        /* Enable parallel compilation. Value: [ true | false ]. Default: true */
    // "typeCheck": false,                      /* Enable typeCheck. Value: [ true | false ]. Default: false */
  },
  "logging": {
    // "level": "info"                          /* Define the log level. Value: [ "debug" | "info" | "warn" | "error" ]. Default: "info" */
  },
  "debugging": {
    // "stacktrace": false                      /* Disable stacktrace compilation. Value: [ true | false ]. Default: false */
  },
  "nodeOptions": {
    // "maxOldSpaceSize": 8192                  /* Enable nodeOptions maxOldSpaceSize compilation. Unit M. Used for the daemon process. Default: 8192*/
    // "exposeGC": true                         /* Enable to trigger garbage collection explicitly. Default: true*/
  }
}

第三步:在products成加入hap编译插件

需要注意hap/hsp/har对应的编译插件不同

products/entry/hvigorfile.ts

TypeScript 复制代码
import { hapTasks } from '@ohos/hvigor-ohos-plugin';
import { hapPlugin } from "@hadss/hmrouter-plugin";

export default {
  system: hapTasks, /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins: [hapPlugin()] // 使用HM Custom plugin to extend the functionality of Hvigor. */
}

第四步:在features的四个包中加入hsp的编译插件-四个hsp包的hvigorfile.ts插件均一致

features/cart/hvigorfile.ts

TypeScript 复制代码
import { hspTasks } from '@ohos/hvigor-ohos-plugin';
import { hspPlugin } from "@hadss/hmrouter-plugin";

export default {
  system: hspTasks, /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins: [hspPlugin()]         /* Custom plugin to extend the functionality of Hvigor. */
}

补充:为了防止底层basic也有可能做一些公共页面,也加入同样的配置

commons/basic/hvigorfile.ts

TypeScript 复制代码
import { hspTasks } from '@ohos/hvigor-ohos-plugin';
import { hspPlugin } from "@hadss/hmrouter-plugin";

export default {
  system: hspTasks, /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins: [hspPlugin()]         /* Custom plugin to extend the functionality of Hvigor. */
}

第五步:在入口Ability中加入HmRouter的初始化上下文

products/entry/src/main/ets/entryability/EntryAbility.ets

TypeScript 复制代码
import { HMRouterMgr } from '@hadss/hmrouter';

export default class EntryAbility extends UIAbility {
  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
    
    // 初始化HmRouter
    HMRouterMgr.init({
      context: this.context,
    });
   
    this.context.getApplicationContext().setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET);
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
  }

最后一步:

定义路由入口

将整个页面的初始化页面作为路由的入口

要求:

●使用HmNavigation作为根容器,包裹所有子页面

●HmNavigaiton外层必须再包裹一个容器组件

●实现一个继承类并且实例化,绑定HmNavigaiton的modifer属性

●使用HmNavigation包裹入口组件

TypeScript 复制代码
import { HomeView } from 'home/Index';
import { CategoryView } from 'category/Index';
import { CartView } from 'cart/Index';
import { MyView } from 'my/Index';
import { BreakpointConstants, BreakPointType, MeiKouConstants } from 'basic';
import { AttributeUpdater } from '@kit.ArkUI';
import { HMDefaultGlobalAnimator, HMNavigation } from '@hadss/hmrouter';

interface TabItem {
  text: string
  normal: ResourceStr
  active: ResourceStr
}


class MyNavModifier extends AttributeUpdater<NavigationAttribute> {
  initializeModifier(instance: NavigationAttribute): void {
    instance.titleMode(NavigationTitleMode.Mini)
    instance.hideTitleBar(true)
  }
}

@Entry
@Component
struct Index {
  @State activeIndex: number = 0
  // 断点值
  @StorageProp(BreakpointConstants.BREAK_POINT_KEY)
  currentBreakpoint: string = BreakpointConstants.SM

  // 获取底部安全高度
  @StorageProp(MeiKouConstants.SafeBottom) safeBottom: number = 0

  modifier: MyNavModifier = new MyNavModifier();

  list: TabItem[] = [
    { text: '首页', normal: $r('app.media.ic_public_home_normal'), active: $r('app.media.ic_public_home_active') },
    { text: '分类', normal: $r('app.media.ic_public_pro_normal'), active: $r('app.media.ic_public_pro_active') },
    { text: '购物袋', normal: $r('app.media.ic_public_cart_normal'), active: $r('app.media.ic_public_cart_active') },
    { text: '我的', normal: $r('app.media.ic_public_my_normal'), active: $r('app.media.ic_public_my_active') },
  ]

  build() {
    Column() {
      HMNavigation({
        navigationId: 'mainNavigation', homePageUrl: 'MainPage',
        options: {
          standardAnimator: HMDefaultGlobalAnimator.STANDARD_ANIMATOR,
          dialogAnimator: HMDefaultGlobalAnimator.DIALOG_ANIMATOR,
          modifier: this.modifier
        },
      }) {
        Tabs({ barPosition: BarPosition.End }) {
          ForEach(this.list, (item: TabItem, index: number) => {
            TabContent() {
              if (index == 0) {
                HomeView()
              } else if (index == 1) {
                CategoryView()
              } else if (index == 2) {
                CartView()
              } else {
                MyView()
              }
            }
            .tabBar(this.TabItemBuilder(item, index))
          })
        }
        .barPosition(
          new BreakPointType({
            sm: BarPosition.End,
            md: BarPosition.End,
            lg: BarPosition.Start
          }).getValue(this.currentBreakpoint)
        )
        .vertical(this.currentBreakpoint === 'lg' ? true : false)
        .scrollable(false)
        .padding({bottom: this.safeBottom})
        .onTabBarClick(index => {
          this.activeIndex = index
        })
      }
    }
  }

  @Builder
  TabItemBuilder(item: TabItem, index: number) {
    Column() {
      Image(this.activeIndex === index ? item.active : item.normal)
        .width(24)
        .aspectRatio(1)
      Text(item.text)
        .fontSize(12)
        .fontColor($r('[basic].color.black'))
    }
    .justifyContent(FlexAlign.SpaceEvenly)
    .height(50)
  }
}
相关推荐
宅小海14 分钟前
14 配置Hadoop集群-配置历史和日志服务
linux·服务器·hadoop
The 旺38 分钟前
《HarmonyOS Next开发实战:从零构建响应式Todo应用的基石》
华为·harmonyos
孤客网络科技工作室1 小时前
每天学一个 Linux 命令(7):cd
java·linux·前端
Industio_触觉智能1 小时前
鸿蒙北向开发OpenHarmony5.0 DevEco Studio开发工具安装与配置
harmonyos·鸿蒙系统·openharmony·开源鸿蒙·鸿蒙开发·嵌入式开发板
hanpfei1 小时前
PipeWire 音频设计与实现分析一——介绍
linux·音视频
tinghai_2161 小时前
华为手机如何文字转语音:智能配音轻松实现
华为·智能手机
Json_181790144801 小时前
python采集淘宝拍立淘按图搜索API接口,json数据示例参考
服务器·前端·数据库
卓应1 小时前
2025年华为HCIP题库分享
网络·华为·智能路由器
想躺在地上晒成地瓜干2 小时前
树莓派超全系列文档--(17)树莓派配置显示器
linux·树莓派·raspberrypi·raspi-config
Brandon汐2 小时前
Linux中常用的文件管理命令
linux·运维·服务器