背景
在项目中使用官方保举的Navigation时,必要在全部的页面上都添加一层NavDestination,在代码阅读上会增加多个层级,而且还要在主页面设置对应名字的跳转等问题,设置起来比力繁琐。看到大佬开发的HMRouter使用起来方便简洁,因此,写下这篇文章记录HMRouter的使用。
插件设置
1.HMRouter安装
在终端中运行下面命令举行第三方库的安装。
- ohpm install @hadss/hmrouter
复制代码
2.添加路由编译插件
修改项目的hvigor/hvigor-config.json文件中的dependencies数组。
- "dependencies": {
- "@hadss/hmrouter-plugin": "^1.0.0-rc.6"
- },
复制代码
3.使用路由编译插件
在项目的entry/hvigorfile.ts文件中添加插件的使用。如果模块是Har则使用harPlugin(),模块是Hsp则使用hspPlugin()
4.工程设置
由于拦截器、生命周期和自界说转场动画会在运行时动态创建实例,因此必要举行如下设置,使得HMRouter路由框架可以动态导入项目中的模块。
在工程目次下的build-profile.json5中,设置useNormalizedOHMUrl属性为true。
HMRouter使用
在UIAbility中初始化路由框架
在OnCreate中初始化路由框架。
- import { HMRouterMgr } from '@hadss/hmrouter';
- onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
- HMRouterMgr.init({
- context: this.context
- })
- hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
- }
复制代码 在首页中界说路由入口
自界说一个NavModifier类,继承AttributeUpdater
- class NavModifier extends AttributeUpdater<NavigationAttribute> {
- initializeModifier(instance: NavigationAttribute): void {
- instance.mode(NavigationMode.Stack);
- instance.navBarWidth('100%');
- instance.hideTitleBar(true);
- instance.hideToolBar(true);
- }
- }
复制代码 然后编写页面代码
- import { HMDefaultGlobalAnimator, HMNavigation, HMRouter, HMRouterMgr } from '@hadss/hmrouter';
- import { AttributeUpdater } from '@kit.ArkUI';
- import {PageModel} from '../../Models/PageModel'
- @Entry
- @Component
- struct HomePage {
- modifier: NavModifier = new NavModifier();
- build() {
- Column() {
- // 使用HMNavigation容器
- HMNavigation({
- navigationId: 'mainNavigation', options: {
- standardAnimator: HMDefaultGlobalAnimator.STANDARD_ANIMATOR,
- dialogAnimator: HMDefaultGlobalAnimator.DIALOG_ANIMATOR,
- modifier: this.modifier
- }
- }) {
- Column({space:20}) {
- Button("TwoPage")
- .width("80%")
- .onClick(() => {
- HMRouterMgr.push({
- navigationId: "mainNavigation",
- pageUrl: "TwoPage"
- })
- })
- }
- .width('100%')
- .height('100%')
- }
- }
- .height('100%')
- .width('100%')
- }
- }
复制代码 HMNavigation 参数解析
- navigationId :容器ID而且全局同一
- homePageUrl:指定默认加载的页面
- navigationOption:全局参数设置。
- modifier:Navigation动态属性设置
- standardAnimator:页面全局动画设置
- dialogAnimator:弹窗全局动画设置
- title:navigation的Title设置
- menus:navigation的menus设置
- toolbar:navigation的toolbar设置
- systemBarStyle:navigation的systemBarStyle设置
页面设置
新建跳转的页面TwoPage,里面按钮使用HMRouterMgr.pop方法实现返回上个页面的操纵。
必须加上@HMRouter装饰器,pageUrl方法来界说页面的名称
- import { HMRouter, HMRouterMgr } from '@hadss/hmrouter'
- @HMRouter({ pageUrl: "TwoPage" })
- @Component
- export struct TwoPage {
- build() {
- Column({ space: 20 }) {
- Button("HomePage")
- .width("80%")
- .onClick(() => {
- HMRouterMgr.pop({
- navigationId: "mainNavigation"
- })
- })
- }
- .height("100%")
- .width("100%")
- }
- }
复制代码 总结
这篇帖子重要关注在HMRouter的情况摆设和简单的页面跳转
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |