当前位置: 首页 > news >正文

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

第一步:全局安装hmrouter依赖

ohpm install @hadss/hmrouter

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

hvigor/hvigor-config.json5

{
  "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

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

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

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

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包裹入口组件

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)
  }
}

相关文章:

  • Vala编程语言教程-属性
  • 鸿蒙OS 5.0 服务能力框架深入剖析
  • 手机零售行业的 AI 破局与创新降本实践 | OceanBase DB大咖说
  • 《第三次世界大战》第一章:战争的前夜
  • Java StringUtils工具类常用方法详解
  • COMPASS:通过残差强化学习和技能合成实现跨具身移动策略
  • 深入解剖Linux进程:从诞生到调度的核心机制
  • 2.1-WAF\CDN\OSS\反向代理\负载均衡
  • linux 硬盘扩展
  • PHP弱类型全面复盘
  • Java 大视界 -- 基于 Java 的大数据隐私计算在医疗影像数据共享中的实践探索(158)
  • 【MinIO】Bucket的生命周期管理
  • python多态、静态方法和类方法
  • Open webui的使用
  • Docker Compose 启动jar包项目
  • dubbo http流量接入dubbo后端服务
  • GRS认证是什么?GRS认证有什么意义?对企业发展的好处
  • 剑指Offer49 -- DP_贪心
  • 高中数学联赛模拟试题第9套几何题
  • 使用YOLOv5训练自定义数据集
  • 重庆南川网站制作公司推荐/网络推广公司口碑
  • 网站推广每天必做的流程/seo品牌优化
  • 网站建设需要什么软件/百度销售系统
  • 小企业网站源码/常见的网络直接营销有哪些
  • 沈阳网站建设培训/浏阳廖主任打人案
  • 亳州市网站建设公司/知名网站排名